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/cask/config.rb
Library/Homebrew/cask/config.rb
# typed: strict # frozen_string_literal: true require "json" require "lazy_object" require "locale" require "extend/hash/keys" module Cask # Configuration for installing casks. # # @api internal class Config ConfigHash = T.type_alias { T::Hash[Symbol, T.any(LazyObject, String, Pathname, T::Array[String])] } DEFAULT_DIRS = T.let( { appdir: "/Applications", keyboard_layoutdir: "/Library/Keyboard Layouts", colorpickerdir: "~/Library/ColorPickers", prefpanedir: "~/Library/PreferencePanes", qlplugindir: "~/Library/QuickLook", mdimporterdir: "~/Library/Spotlight", dictionarydir: "~/Library/Dictionaries", fontdir: "~/Library/Fonts", servicedir: "~/Library/Services", input_methoddir: "~/Library/Input Methods", internet_plugindir: "~/Library/Internet Plug-Ins", audio_unit_plugindir: "~/Library/Audio/Plug-Ins/Components", vst_plugindir: "~/Library/Audio/Plug-Ins/VST", vst3_plugindir: "~/Library/Audio/Plug-Ins/VST3", screen_saverdir: "~/Library/Screen Savers", }.freeze, T::Hash[Symbol, String], ) # runtime recursive evaluation forces the LazyObject to be evaluated T::Sig::WithoutRuntime.sig { returns(T::Hash[Symbol, T.any(LazyObject, String)]) } def self.defaults { languages: LazyObject.new { ::OS::Mac.languages }, }.merge(DEFAULT_DIRS).freeze end sig { params(args: Homebrew::CLI::Args).returns(T.attached_class) } def self.from_args(args) # FIXME: T.unsafe is a workaround for methods that are only defined when `cask_options` # is invoked on the parser. (These could be captured by a DSL compiler instead.) args = T.unsafe(args) new(explicit: { appdir: args.appdir, keyboard_layoutdir: args.keyboard_layoutdir, colorpickerdir: args.colorpickerdir, prefpanedir: args.prefpanedir, qlplugindir: args.qlplugindir, mdimporterdir: args.mdimporterdir, dictionarydir: args.dictionarydir, fontdir: args.fontdir, servicedir: args.servicedir, input_methoddir: args.input_methoddir, internet_plugindir: args.internet_plugindir, audio_unit_plugindir: args.audio_unit_plugindir, vst_plugindir: args.vst_plugindir, vst3_plugindir: args.vst3_plugindir, screen_saverdir: args.screen_saverdir, languages: args.language, }.compact) end sig { params(json: String, ignore_invalid_keys: T::Boolean).returns(T.attached_class) } def self.from_json(json, ignore_invalid_keys: false) config = JSON.parse(json, symbolize_names: true) new( default: config.fetch(:default, {}), env: config.fetch(:env, {}), explicit: config.fetch(:explicit, {}), ignore_invalid_keys:, ) end sig { params(config: ConfigHash).returns(ConfigHash) } def self.canonicalize(config) config.to_h do |k, v| if DEFAULT_DIRS.key?(k) raise TypeError, "Invalid path for default dir #{k}: #{v.inspect}" if v.is_a?(Array) [k, Pathname(v.to_s).expand_path] else [k, v] end end end # Get the explicit configuration. # # @api internal sig { returns(ConfigHash) } attr_accessor :explicit sig { params( default: T.nilable(ConfigHash), env: T.nilable(ConfigHash), explicit: ConfigHash, ignore_invalid_keys: T::Boolean, ).void } def initialize(default: nil, env: nil, explicit: {}, ignore_invalid_keys: false) if default @default = T.let( self.class.canonicalize(self.class.defaults.merge(default)), T.nilable(ConfigHash), ) end if env @env = T.let( self.class.canonicalize(env), T.nilable(ConfigHash), ) end @explicit = T.let( self.class.canonicalize(explicit), ConfigHash, ) if ignore_invalid_keys @env&.delete_if { |key, _| self.class.defaults.keys.exclude?(key) } @explicit.delete_if { |key, _| self.class.defaults.keys.exclude?(key) } return end @env&.assert_valid_keys(*self.class.defaults.keys) @explicit.assert_valid_keys(*self.class.defaults.keys) end sig { returns(ConfigHash) } def default @default ||= self.class.canonicalize(self.class.defaults) end sig { returns(ConfigHash) } def env @env ||= self.class.canonicalize( Homebrew::EnvConfig.cask_opts .select { |arg| arg.include?("=") } .map { |arg| T.cast(arg.split("=", 2), [String, String]) } .to_h do |(flag, value)| key = flag.sub(/^--/, "") # converts --language flag to :languages config key if key == "language" key = "languages" value = value.split(",") end [key.to_sym, value] end, ) end sig { returns(Pathname) } def binarydir @binarydir ||= T.let(HOMEBREW_PREFIX/"bin", T.nilable(Pathname)) end sig { returns(Pathname) } def manpagedir @manpagedir ||= T.let(HOMEBREW_PREFIX/"share/man", T.nilable(Pathname)) end sig { returns(Pathname) } def bash_completion @bash_completion ||= T.let(HOMEBREW_PREFIX/"etc/bash_completion.d", T.nilable(Pathname)) end sig { returns(Pathname) } def zsh_completion @zsh_completion ||= T.let(HOMEBREW_PREFIX/"share/zsh/site-functions", T.nilable(Pathname)) end sig { returns(Pathname) } def fish_completion @fish_completion ||= T.let(HOMEBREW_PREFIX/"share/fish/vendor_completions.d", T.nilable(Pathname)) end sig { returns(T::Array[String]) } def languages [ *explicit.fetch(:languages, []), *env.fetch(:languages, []), *default.fetch(:languages, []), ].uniq.select do |lang| # Ensure all languages are valid. Locale.parse(lang) true rescue Locale::ParserError false end end sig { params(languages: T::Array[String]).void } def languages=(languages) explicit[:languages] = languages end DEFAULT_DIRS.each_key do |dir| define_method(dir) do T.bind(self, Config) explicit.fetch(dir, env.fetch(dir, default.fetch(dir))) end define_method(:"#{dir}=") do |path| T.bind(self, Config) explicit[dir] = Pathname(path).expand_path end end sig { params(other: Config).returns(T.self_type) } def merge(other) self.class.new(explicit: other.explicit.merge(explicit)) end sig { params(options: T.untyped).returns(String) } def to_json(*options) { default:, env:, explicit:, }.to_json(*options) end end end require "extend/os/cask/config"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/auditor.rb
Library/Homebrew/cask/auditor.rb
# typed: strict # frozen_string_literal: true require "cask/audit" require "utils/output" module Cask # Helper class for auditing all available languages of a cask. class Auditor include ::Utils::Output::Mixin # TODO: use argument forwarding (...) when Sorbet supports it in strict mode sig { params( cask: ::Cask::Cask, audit_download: T::Boolean, audit_online: T.nilable(T::Boolean), audit_strict: T.nilable(T::Boolean), audit_signing: T.nilable(T::Boolean), audit_new_cask: T.nilable(T::Boolean), quarantine: T::Boolean, any_named_args: T::Boolean, language: T.nilable(String), only: T::Array[String], except: T::Array[String] ).returns(T::Set[String]) } def self.audit( cask, audit_download: false, audit_online: nil, audit_strict: nil, audit_signing: nil, audit_new_cask: nil, quarantine: false, any_named_args: false, language: nil, only: [], except: [] ) new( cask, audit_download:, audit_online:, audit_strict:, audit_signing:, audit_new_cask:, quarantine:, any_named_args:, language:, only:, except: ).audit end sig { returns(::Cask::Cask) } attr_reader :cask sig { returns(T.nilable(String)) } attr_reader :language sig { params( cask: ::Cask::Cask, audit_download: T::Boolean, audit_online: T.nilable(T::Boolean), audit_strict: T.nilable(T::Boolean), audit_signing: T.nilable(T::Boolean), audit_new_cask: T.nilable(T::Boolean), quarantine: T::Boolean, any_named_args: T::Boolean, language: T.nilable(String), only: T::Array[String], except: T::Array[String] ).void } def initialize( cask, audit_download: false, audit_online: nil, audit_strict: nil, audit_signing: nil, audit_new_cask: nil, quarantine: false, any_named_args: false, language: nil, only: [], except: [] ) @cask = cask @audit_download = audit_download @audit_online = audit_online @audit_new_cask = audit_new_cask @audit_strict = audit_strict @audit_signing = audit_signing @quarantine = quarantine @any_named_args = any_named_args @language = language @only = only @except = except end LANGUAGE_BLOCK_LIMIT = 10 sig { returns(T::Set[String]) } def audit errors = Set.new if !language && !(blocks = language_blocks).empty? sample_languages = if blocks.length > LANGUAGE_BLOCK_LIMIT && !@audit_new_cask sample_keys = T.must(blocks.keys.sample(LANGUAGE_BLOCK_LIMIT)) ohai "Auditing a sample of available languages for #{cask}: " \ "#{sample_keys.map { |lang| lang[0].to_s }.to_sentence}" blocks.select { |k| sample_keys.include?(k) } else blocks end sample_languages.each_key do |l| audit = audit_languages(l) if audit.summary.present? && output_summary?(audit) ohai "Auditing language: #{l.map { |lang| "'#{lang}'" }.to_sentence}" if output_summary? puts audit.summary end errors += audit.errors end else audit = audit_cask_instance(cask) puts audit.summary if audit.summary.present? && output_summary?(audit) errors += audit.errors end errors end private sig { params(audit: T.nilable(Audit)).returns(T::Boolean) } def output_summary?(audit = nil) return true if @any_named_args return true if @audit_strict return false if audit.nil? audit.errors? end sig { params(languages: T::Array[String]).returns(::Cask::Audit) } def audit_languages(languages) original_config = cask.config localized_config = original_config.merge(Config.new(explicit: { languages: })) cask.config = localized_config audit_cask_instance(cask) ensure cask.config = original_config end sig { params(cask: ::Cask::Cask).returns(::Cask::Audit) } def audit_cask_instance(cask) audit = Audit.new( cask, online: @audit_online, strict: @audit_strict, signing: @audit_signing, new_cask: @audit_new_cask, download: @audit_download, quarantine: @quarantine, only: @only, except: @except, ) audit.run! end sig { returns(T::Hash[T::Array[String], T.proc.returns(T.untyped)]) } def language_blocks cask.instance_variable_get(:@dsl).instance_variable_get(:@language_blocks) end end 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/cask.rb
Library/Homebrew/cask/cask.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "bundle_version" require "cask/cask_loader" require "cask/config" require "cask/dsl" require "cask/metadata" require "cask/tab" require "utils/bottles" require "utils/output" require "api_hashable" module Cask # An instance of a cask. class Cask extend Forwardable extend APIHashable extend ::Utils::Output::Mixin include Metadata # The token of this {Cask}. # # @api internal attr_reader :token # The configuration of this {Cask}. # # @api internal attr_reader :config attr_reader :sourcefile_path, :source, :default_config, :loader attr_accessor :download, :allow_reassignment def self.all(eval_all: false) if !eval_all && !Homebrew::EnvConfig.eval_all? raise ArgumentError, "Cask::Cask#all cannot be used without `--eval-all` or `HOMEBREW_EVAL_ALL=1`" end # Load core casks from tokens so they load from the API when the core cask is not tapped. tokens_and_files = CoreCaskTap.instance.cask_tokens tokens_and_files += Tap.reject(&:core_cask_tap?).flat_map(&:cask_files) tokens_and_files.filter_map do |token_or_file| CaskLoader.load(token_or_file) rescue CaskUnreadableError => e opoo e.message nil end end def tap return super if block_given? # Object#tap @tap end sig { params( token: String, sourcefile_path: T.nilable(Pathname), source: T.nilable(String), tap: T.nilable(Tap), loaded_from_api: T::Boolean, api_source: T.nilable(T::Hash[String, T.untyped]), config: T.nilable(Config), allow_reassignment: T::Boolean, loader: T.nilable(CaskLoader::ILoader), block: T.nilable(T.proc.bind(DSL).void), ).void } def initialize(token, sourcefile_path: nil, source: nil, tap: nil, loaded_from_api: false, api_source: nil, config: nil, allow_reassignment: false, loader: nil, &block) @token = token @sourcefile_path = sourcefile_path @source = source @tap = tap @allow_reassignment = allow_reassignment @loaded_from_api = loaded_from_api @api_source = api_source @loader = loader # Sorbet has trouble with bound procs assigned to instance variables: # https://github.com/sorbet/sorbet/issues/6843 instance_variable_set(:@block, block) @default_config = config || Config.new self.config = if config_path.exist? Config.from_json(File.read(config_path), ignore_invalid_keys: true) else @default_config end end sig { returns(T::Boolean) } def loaded_from_api? = @loaded_from_api sig { returns(T.nilable(T::Hash[String, T.untyped])) } attr_reader :api_source # An old name for the cask. sig { returns(T::Array[String]) } def old_tokens @old_tokens ||= if (tap = self.tap) Tap.tap_migration_oldnames(tap, token) + tap.cask_reverse_renames.fetch(token, []) else [] end end def config=(config) @config = config refresh end def refresh @dsl = DSL.new(self) return unless @block @dsl.instance_eval(&@block) @dsl.add_implicit_macos_dependency @dsl.language_eval end def_delegators :@dsl, *::Cask::DSL::DSL_METHODS sig { params(caskroom_path: Pathname).returns(T::Array[[String, String]]) } def timestamped_versions(caskroom_path: self.caskroom_path) pattern = metadata_timestamped_path(version: "*", timestamp: "*", caskroom_path:).to_s relative_paths = Pathname.glob(pattern) .map { |p| p.relative_path_from(p.parent.parent) } # Sorbet is unaware that Pathname is sortable: https://github.com/sorbet/sorbet/issues/6844 T.unsafe(relative_paths).sort_by(&:basename) # sort by timestamp .map { |p| p.split.map(&:to_s) } end # The fully-qualified token of this {Cask}. # # @api internal def full_token return token if tap.nil? return token if tap.core_cask_tap? "#{tap.name}/#{token}" end # Alias for {#full_token}. # # @api internal def full_name = full_token sig { returns(T::Boolean) } def installed? installed_caskfile&.exist? || false end sig { returns(T::Boolean) } def font? artifacts.all?(Artifact::Font) end sig { returns(T::Boolean) } def supports_macos? = true sig { returns(T::Boolean) } def supports_linux? return true if font? return false if artifacts.any? do |artifact| ::Cask::Artifact::MACOS_ONLY_ARTIFACTS.include?(artifact.class) end @dsl.os.present? end # The caskfile is needed during installation when there are # `*flight` blocks or the cask has multiple languages def caskfile_only? languages.any? || artifacts.any?(Artifact::AbstractFlightBlock) end def uninstall_flight_blocks? artifacts.any? do |artifact| case artifact when Artifact::PreflightBlock artifact.directives.key?(:uninstall_preflight) when Artifact::PostflightBlock artifact.directives.key?(:uninstall_postflight) end end end sig { returns(T.nilable(Time)) } def install_time # <caskroom_path>/.metadata/<version>/<timestamp>/Casks/<token>.{rb,json} -> <timestamp> caskfile = installed_caskfile Time.strptime(caskfile.dirname.dirname.basename.to_s, Metadata::TIMESTAMP_FORMAT) if caskfile end sig { returns(T.nilable(Pathname)) } def installed_caskfile installed_caskroom_path = caskroom_path installed_token = token # Check if the cask is installed with an old name. old_tokens.each do |old_token| old_caskroom_path = Caskroom.path/old_token next if !old_caskroom_path.directory? || old_caskroom_path.symlink? installed_caskroom_path = old_caskroom_path installed_token = old_token break end installed_version = timestamped_versions(caskroom_path: installed_caskroom_path).last return unless installed_version caskfile_dir = metadata_main_container_path(caskroom_path: installed_caskroom_path) .join(*installed_version, "Casks") ["json", "rb"] .map { |ext| caskfile_dir.join("#{installed_token}.#{ext}") } .find(&:exist?) end sig { returns(T.nilable(String)) } def installed_version return unless (installed_caskfile = self.installed_caskfile) # <caskroom_path>/.metadata/<version>/<timestamp>/Casks/<token>.{rb,json} -> <version> installed_caskfile.dirname.dirname.dirname.basename.to_s end sig { returns(T.nilable(String)) } def bundle_short_version bundle_version&.short_version end sig { returns(T.nilable(String)) } def bundle_long_version bundle_version&.version end def tab Tab.for_cask(self) end def config_path metadata_main_container_path/"config.json" end def checksumable? return false if (url = self.url).nil? DownloadStrategyDetector.detect(url.to_s, url.using) <= AbstractFileDownloadStrategy end def download_sha_path metadata_main_container_path/"LATEST_DOWNLOAD_SHA256" end def new_download_sha require "cask/installer" # Call checksumable? before hashing @new_download_sha ||= Installer.new(self, verify_download_integrity: false) .download(quiet: true) .instance_eval { |x| Digest::SHA256.file(x).hexdigest } end def outdated_download_sha? return true unless checksumable? current_download_sha = download_sha_path.read if download_sha_path.exist? current_download_sha.blank? || current_download_sha != new_download_sha end sig { returns(Pathname) } def caskroom_path @caskroom_path ||= Caskroom.path.join(token) end # Check if the installed cask is outdated. # # @api internal def outdated?(greedy: false, greedy_latest: false, greedy_auto_updates: false) !outdated_version(greedy:, greedy_latest:, greedy_auto_updates:).nil? end def outdated_version(greedy: false, greedy_latest: false, greedy_auto_updates: false) # special case: tap version is not available return if version.nil? if version.latest? return installed_version if (greedy || greedy_latest) && outdated_download_sha? return elsif auto_updates && !greedy && !greedy_auto_updates return end # not outdated unless there is a different version on tap return if installed_version == version installed_version end def outdated_info(greedy, verbose, json, greedy_latest, greedy_auto_updates) return token if !verbose && !json installed_version = outdated_version(greedy:, greedy_latest:, greedy_auto_updates:).to_s if json { name: token, installed_versions: [installed_version], current_version: version, } else "#{token} (#{installed_version}) != #{version}" end end def ruby_source_path return @ruby_source_path if defined?(@ruby_source_path) return unless sourcefile_path return unless tap @ruby_source_path = sourcefile_path.relative_path_from(tap.path) end sig { returns(T::Hash[Symbol, String]) } def ruby_source_checksum @ruby_source_checksum ||= { sha256: Digest::SHA256.file(sourcefile_path).hexdigest, }.freeze end def languages @languages ||= @dsl.languages end def tap_git_head @tap_git_head ||= tap&.git_head rescue TapUnavailableError nil end sig { params(cask_struct: Homebrew::API::CaskStruct).void } def populate_from_api!(cask_struct) raise ArgumentError, "Expected cask to be loaded from the API" unless loaded_from_api? @languages = cask_struct.languages @tap_git_head = cask_struct.tap_git_head @ruby_source_path = cask_struct.ruby_source_path @ruby_source_checksum = cask_struct.ruby_source_checksum end # @api public sig { returns(String) } def to_s = token sig { returns(String) } def inspect "#<Cask #{token}#{sourcefile_path&.to_s&.prepend(" ")}>" end def hash token.hash end def eql?(other) instance_of?(other.class) && token == other.token end alias == eql? def to_h { "token" => token, "full_token" => full_name, "old_tokens" => old_tokens, "tap" => tap&.name, "name" => name, "desc" => desc, "homepage" => homepage, "url" => url, "url_specs" => url_specs, "version" => version, "autobump" => autobump?, "no_autobump_message" => no_autobump_message, "skip_livecheck" => livecheck.skip?, "installed" => installed_version, "installed_time" => install_time&.to_i, "bundle_version" => bundle_long_version, "bundle_short_version" => bundle_short_version, "outdated" => outdated?, "sha256" => sha256, "artifacts" => artifacts_list, "caveats" => (Tty.strip_ansi(caveats) unless caveats.empty?), "depends_on" => depends_on, "conflicts_with" => conflicts_with, "container" => container&.pairs, "rename" => rename_list, "auto_updates" => auto_updates, "deprecated" => deprecated?, "deprecation_date" => deprecation_date, "deprecation_reason" => deprecation_reason, "deprecation_replacement_formula" => deprecation_replacement_formula, "deprecation_replacement_cask" => deprecation_replacement_cask, "deprecate_args" => deprecate_args, "disabled" => disabled?, "disable_date" => disable_date, "disable_reason" => disable_reason, "disable_replacement_formula" => disable_replacement_formula, "disable_replacement_cask" => disable_replacement_cask, "disable_args" => disable_args, "tap_git_head" => tap_git_head, "languages" => languages, "ruby_source_path" => ruby_source_path, "ruby_source_checksum" => ruby_source_checksum, } end HASH_KEYS_TO_SKIP = %w[outdated installed versions].freeze private_constant :HASH_KEYS_TO_SKIP def to_hash_with_variations if loaded_from_api? && (json_cask = api_source) && !Homebrew::EnvConfig.no_install_from_api? return api_to_local_hash(json_cask.dup) end hash = to_h variations = {} if @dsl.on_system_blocks_exist? begin OnSystem::VALID_OS_ARCH_TAGS.each do |bottle_tag| next if bottle_tag.linux? && @dsl.os.nil? next if bottle_tag.macos? && depends_on.macos && !@dsl.depends_on_set_in_block? && !depends_on.macos.allows?(bottle_tag.to_macos_version) Homebrew::SimulateSystem.with_tag(bottle_tag) do refresh to_h.each do |key, value| next if HASH_KEYS_TO_SKIP.include? key next if value.to_s == hash[key].to_s variations[bottle_tag.to_sym] ||= {} variations[bottle_tag.to_sym][key] = value end end end ensure refresh end end hash["variations"] = variations hash end def artifacts_list(uninstall_only: false) artifacts.filter_map do |artifact| case artifact when Artifact::AbstractFlightBlock uninstall_flight_block = artifact.directives.key?(:uninstall_preflight) || artifact.directives.key?(:uninstall_postflight) next if uninstall_only && !uninstall_flight_block # Only indicate whether this block is used as we don't load it from the API { artifact.summarize.to_sym => nil } else zap_artifact = artifact.is_a?(Artifact::Zap) uninstall_artifact = artifact.respond_to?(:uninstall_phase) || artifact.respond_to?(:post_uninstall_phase) next if uninstall_only && !zap_artifact && !uninstall_artifact { artifact.class.dsl_key => artifact.to_args } end end end def rename_list(uninstall_only: false) rename.filter_map do |rename| { from: rename.from, to: rename.to } end end private sig { returns(T.nilable(Homebrew::BundleVersion)) } def bundle_version @bundle_version ||= if (bundle = artifacts.find { |a| a.is_a?(Artifact::App) }&.target) && (plist = Pathname("#{bundle}/Contents/Info.plist")) && plist.exist? && plist.readable? Homebrew::BundleVersion.from_info_plist(plist) end end def api_to_local_hash(hash) hash["token"] = token hash["installed"] = installed_version hash["outdated"] = outdated? hash end def url_specs url&.specs.dup.tap do |url_specs| case url_specs&.dig(:user_agent) when :default url_specs.delete(:user_agent) when Symbol url_specs[:user_agent] = ":#{url_specs[:user_agent]}" 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/cask/quarantine.rb
Library/Homebrew/cask/quarantine.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "development_tools" require "cask/exceptions" require "system_command" require "utils/output" module Cask # Helper module for quarantining files. module Quarantine extend SystemCommand::Mixin extend ::Utils::Output::Mixin QUARANTINE_ATTRIBUTE = "com.apple.quarantine" QUARANTINE_SCRIPT = (HOMEBREW_LIBRARY_PATH/"cask/utils/quarantine.swift").freeze COPY_XATTRS_SCRIPT = (HOMEBREW_LIBRARY_PATH/"cask/utils/copy-xattrs.swift").freeze def self.swift @swift ||= begin # /usr/bin/swift (which runs via xcrun) adds `/usr/local/include` to the top of the include path, # which allows really broken local setups to break our Swift usage here. Using the underlying # Swift executable directly however (returned by `xcrun -find`) avoids this CPATH mess. xcrun_swift = ::Utils.popen_read("/usr/bin/xcrun", "-find", "swift", err: :close).chomp if $CHILD_STATUS.success? && File.executable?(xcrun_swift) xcrun_swift else DevelopmentTools.locate("swift") end end end private_class_method :swift def self.xattr @xattr ||= DevelopmentTools.locate("xattr") end private_class_method :xattr def self.swift_target_args ["-target", "#{Hardware::CPU.arch}-apple-macosx#{MacOS.version}"] end private_class_method :swift_target_args sig { returns([Symbol, T.nilable(String)]) } def self.check_quarantine_support odebug "Checking quarantine support" check_output = nil status = if xattr.nil? || !system_command(xattr, args: ["-h"], print_stderr: false).success? odebug "There's no working version of `xattr` on this system." :xattr_broken elsif swift.nil? odebug "Swift is not available on this system." :no_swift else api_check = system_command(swift, args: [*swift_target_args, QUARANTINE_SCRIPT], print_stderr: false) exit_status = api_check.exit_status check_output = api_check.merged_output.to_s.strip error_output = api_check.stderr.to_s.strip case exit_status when 2 odebug "Quarantine is available." :quarantine_available when 1 # Swift script ran but failed (likely due to CLT issues) odebug "Swift quarantine script failed: #{error_output}" if error_output.include?("does not exist") || error_output.include?("No such file") :swift_broken_clt elsif error_output.include?("compiler") || error_output.include?("SDK") :swift_compilation_failed else :swift_runtime_error end when 127 # Command not found or execution failed odebug "Swift execution failed with exit status 127" :swift_not_executable else odebug "Swift returned unexpected exit status: #{exit_status}" :swift_unexpected_error end end [status, check_output] end sig { returns(T::Boolean) } def self.available? @quarantine_support ||= check_quarantine_support @quarantine_support[0] == :quarantine_available end def self.detect(file) return if file.nil? odebug "Verifying Gatekeeper status of #{file}" quarantine_status = !status(file).empty? odebug "#{file} is #{quarantine_status ? "quarantined" : "not quarantined"}" quarantine_status end def self.status(file) system_command(xattr, args: ["-p", QUARANTINE_ATTRIBUTE, file], print_stderr: false).stdout.rstrip end def self.toggle_no_translocation_bit(attribute) fields = attribute.split(";") # Fields: status, epoch, download agent, event ID # Let's toggle the app translocation bit, bit 8 # http://www.openradar.me/radar?id=5022734169931776 fields[0] = (fields[0].to_i(16) | 0x0100).to_s(16).rjust(4, "0") fields.join(";") end def self.release!(download_path: nil) return unless detect(download_path) odebug "Releasing #{download_path} from quarantine" quarantiner = system_command(xattr, args: [ "-d", QUARANTINE_ATTRIBUTE, download_path, ], print_stderr: false) return if quarantiner.success? raise CaskQuarantineReleaseError.new(download_path, quarantiner.stderr) end def self.cask!(cask: nil, download_path: nil, action: true) return if cask.nil? || download_path.nil? return if detect(download_path) odebug "Quarantining #{download_path}" quarantiner = system_command(swift, args: [ *swift_target_args, QUARANTINE_SCRIPT, download_path, cask.url.to_s, cask.homepage.to_s, ], print_stderr: false) return if quarantiner.success? case quarantiner.exit_status when 2 raise CaskQuarantineError.new(download_path, "Insufficient parameters") else raise CaskQuarantineError.new(download_path, quarantiner.stderr) end end def self.propagate(from: nil, to: nil) return if from.nil? || to.nil? raise CaskError, "#{from} was not quarantined properly." unless detect(from) odebug "Propagating quarantine from #{from} to #{to}" quarantine_status = toggle_no_translocation_bit(status(from)) resolved_paths = Pathname.glob(to/"**/*", File::FNM_DOTMATCH).reject(&:symlink?) system_command!("/usr/bin/xargs", args: [ "-0", "--", "chmod", "-h", "u+w", ], input: resolved_paths.join("\0")) quarantiner = system_command("/usr/bin/xargs", args: [ "-0", "--", xattr, "-w", QUARANTINE_ATTRIBUTE, quarantine_status, ], input: resolved_paths.join("\0"), print_stderr: false) return if quarantiner.success? raise CaskQuarantinePropagationError.new(to, quarantiner.stderr) end sig { params(from: Pathname, to: Pathname, command: T.class_of(SystemCommand)).void } def self.copy_xattrs(from, to, command:) odebug "Copying xattrs from #{from} to #{to}" command.run!( swift, args: [ *swift_target_args, COPY_XATTRS_SCRIPT, from, to, ], sudo: !to.writable?, ) end # Ensures that Homebrew has permission to update apps on macOS Ventura. # This may be granted either through the App Management toggle or the Full Disk Access toggle. # The system will only show a prompt for App Management, so we ask the user to grant that. sig { params(app: Pathname, command: T.class_of(SystemCommand)).returns(T::Boolean) } def self.app_management_permissions_granted?(app:, command:) return true unless app.directory? # To get macOS to prompt the user for permissions, we need to actually attempt to # modify a file in the app. test_file = app/".homebrew-write-test" # We can't use app.writable? here because that conflates several access checks, # including both file ownership and whether system permissions are granted. # Here we just want to check whether sudo would be needed. looks_writable_without_sudo = if app.owned? app.lstat.mode.anybits?(0200) elsif app.grpowned? app.lstat.mode.anybits?(0020) else app.lstat.mode.anybits?(0002) end if looks_writable_without_sudo begin File.write(test_file, "") test_file.delete return true rescue Errno::EACCES, Errno::EPERM # Using error handler below end else begin command.run!( "touch", args: [ test_file, ], print_stderr: false, sudo: true, ) command.run!( "rm", args: [ test_file, ], print_stderr: false, sudo: true, ) return true rescue ErrorDuringExecution => e # We only want to handle "touch" errors here; propagate "sudo" errors up raise e unless e.stderr.include?("touch: #{test_file}: Operation not permitted") end end # Allow undocumented way to skip the prompt. if ENV["HOMEBREW_NO_APP_MANAGEMENT_PERMISSIONS_PROMPT"] opoo <<~EOF Your terminal does not have App Management permissions, so Homebrew will delete and reinstall the app. This may result in some configurations (like notification settings or location in the Dock/Launchpad) being lost. To fix this, go to System Settings → Privacy & Security → App Management and add or enable your terminal. EOF end false end end end require "extend/os/cask/quarantine"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/pkg.rb
Library/Homebrew/cask/pkg.rb
# typed: strict # frozen_string_literal: true require "cask/macos" require "utils/output" module Cask # Helper class for uninstalling `.pkg` installers. class Pkg include ::Utils::Output::Mixin sig { params(regexp: String, command: T.class_of(SystemCommand)).returns(T::Array[Pkg]) } def self.all_matching(regexp, command) command.run("/usr/sbin/pkgutil", args: ["--pkgs=#{regexp}"]).stdout.split("\n").map do |package_id| new(package_id.chomp, command) end end sig { returns(String) } attr_reader :package_id sig { params(package_id: String, command: T.class_of(SystemCommand)).void } def initialize(package_id, command = SystemCommand) @package_id = package_id @command = command end sig { void } def uninstall unless pkgutil_bom_files.empty? odebug "Deleting pkg files" @command.run!( "/usr/bin/xargs", args: ["-0", "--", "/bin/rm", "--"], input: pkgutil_bom_files.join("\0"), sudo: true, sudo_as_root: true, ) end unless pkgutil_bom_specials.empty? odebug "Deleting pkg symlinks and special files" @command.run!( "/usr/bin/xargs", args: ["-0", "--", "/bin/rm", "--"], input: pkgutil_bom_specials.join("\0"), sudo: true, sudo_as_root: true, ) end unless pkgutil_bom_dirs.empty? odebug "Deleting pkg directories" rmdir(deepest_path_first(pkgutil_bom_dirs)) end rmdir(root) unless MacOS.undeletable?(root) forget end sig { void } def forget odebug "Unregistering pkg receipt (aka forgetting)" @command.run!( "/usr/sbin/pkgutil", args: ["--forget", package_id], sudo: true, sudo_as_root: true, ) end sig { returns(T::Array[Pathname]) } def pkgutil_bom_files @pkgutil_bom_files ||= T.let(pkgutil_bom_all.select(&:file?) - pkgutil_bom_specials, T.nilable(T::Array[Pathname])) end sig { returns(T::Array[Pathname]) } def pkgutil_bom_specials @pkgutil_bom_specials ||= T.let(pkgutil_bom_all.select { special?(it) }, T.nilable(T::Array[Pathname])) end sig { returns(T::Array[Pathname]) } def pkgutil_bom_dirs @pkgutil_bom_dirs ||= T.let(pkgutil_bom_all.select(&:directory?) - pkgutil_bom_specials, T.nilable(T::Array[Pathname])) end sig { returns(T::Array[Pathname]) } def pkgutil_bom_all @pkgutil_bom_all ||= T.let( @command.run!("/usr/sbin/pkgutil", args: ["--files", package_id]) .stdout .split("\n") .map { |path| root.join(path) } .reject { |path| MacOS.undeletable?(path) }, T.nilable(T::Array[Pathname]), ) end sig { returns(Pathname) } def root @root ||= T.let(Pathname.new(info.fetch("volume")).join(info.fetch("install-location")), T.nilable(Pathname)) end sig { returns(T.untyped) } def info @info ||= T.let(@command.run!("/usr/sbin/pkgutil", args: ["--pkg-info-plist", package_id]).plist, T.untyped) end private sig { params(path: Pathname).returns(T::Boolean) } def special?(path) path.symlink? || path.chardev? || path.blockdev? end # Helper script to delete empty directories after deleting `.DS_Store` files and broken symlinks. # Needed in order to execute all file operations with `sudo`. RMDIR_SH = T.let((HOMEBREW_LIBRARY_PATH/"cask/utils/rmdir.sh").freeze, Pathname) private_constant :RMDIR_SH sig { params(path: T.any(Pathname, T::Array[Pathname])).void } def rmdir(path) @command.run!( "/usr/bin/xargs", args: ["-0", "--", RMDIR_SH.to_s], input: Array(path).join("\0"), sudo: true, sudo_as_root: true, ) end sig { params(paths: T::Array[Pathname]).returns(T::Array[Pathname]) } def deepest_path_first(paths) paths.sort_by { |path| -path.to_s.split(File::SEPARATOR).count } end end 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/cache.rb
Library/Homebrew/cask/cache.rb
# typed: strict # frozen_string_literal: true module Cask # Helper functions for the cask cache. module Cache sig { returns(Pathname) } def self.path @path ||= T.let(HOMEBREW_CACHE/"Cask", T.nilable(Pathname)) end end 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/migrator.rb
Library/Homebrew/cask/migrator.rb
# typed: strict # frozen_string_literal: true require "cask/cask_loader" require "utils/inreplace" require "utils/output" module Cask class Migrator include ::Utils::Output::Mixin sig { returns(Cask) } attr_reader :old_cask, :new_cask sig { params(old_cask: Cask, new_cask: Cask).void } def initialize(old_cask, new_cask) raise CaskNotInstalledError, new_cask unless new_cask.installed? @old_cask = old_cask @new_cask = new_cask end sig { params(new_cask: Cask, dry_run: T::Boolean).void } def self.migrate_if_needed(new_cask, dry_run: false) old_tokens = new_cask.old_tokens return if old_tokens.empty? return unless (installed_caskfile = new_cask.installed_caskfile) old_cask = CaskLoader.load(installed_caskfile) return if new_cask.token == old_cask.token migrator = new(old_cask, new_cask) migrator.migrate(dry_run:) end sig { params(dry_run: T::Boolean).void } def migrate(dry_run: false) old_token = old_cask.token new_token = new_cask.token old_caskroom_path = old_cask.caskroom_path new_caskroom_path = new_cask.caskroom_path old_caskfile = old_cask.installed_caskfile return if old_caskfile.nil? old_installed_caskfile = old_caskfile.relative_path_from(old_caskroom_path) new_installed_caskfile = old_installed_caskfile.dirname/old_installed_caskfile.basename.sub( old_token, new_token, ) if dry_run oh1 "Would migrate cask #{Formatter.identifier(old_token)} to #{Formatter.identifier(new_token)}" puts "cp -r #{old_caskroom_path} #{new_caskroom_path}" puts "mv #{new_caskroom_path}/#{old_installed_caskfile} #{new_caskroom_path}/#{new_installed_caskfile}" puts "rm -r #{old_caskroom_path}" puts "ln -s #{new_caskroom_path.basename} #{old_caskroom_path}" else oh1 "Migrating cask #{Formatter.identifier(old_token)} to #{Formatter.identifier(new_token)}" begin FileUtils.cp_r old_caskroom_path, new_caskroom_path FileUtils.mv new_caskroom_path/old_installed_caskfile, new_caskroom_path/new_installed_caskfile self.class.replace_caskfile_token(new_caskroom_path/new_installed_caskfile, old_token, new_token) rescue => e FileUtils.rm_rf new_caskroom_path raise e end FileUtils.rm_r old_caskroom_path FileUtils.ln_s new_caskroom_path.basename, old_caskroom_path end end sig { params(path: Pathname, old_token: String, new_token: String).void } def self.replace_caskfile_token(path, old_token, new_token) case path.extname when ".rb" ::Utils::Inreplace.inreplace path, /\A\s*cask\s+"#{Regexp.escape(old_token)}"/, "cask #{new_token.inspect}" when ".json" json = JSON.parse(path.read) json["token"] = new_token path.atomic_write json.to_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/cask/metadata.rb
Library/Homebrew/cask/metadata.rb
# typed: strict # frozen_string_literal: true require "utils/output" module Cask # Helper module for reading and writing cask metadata. module Metadata extend T::Helpers include ::Utils::Output::Mixin METADATA_SUBDIR = ".metadata" TIMESTAMP_FORMAT = "%Y%m%d%H%M%S.%L" requires_ancestor { Cask } sig { params(caskroom_path: Pathname).returns(Pathname) } def metadata_main_container_path(caskroom_path: self.caskroom_path) caskroom_path.join(METADATA_SUBDIR) end sig { params(version: T.nilable(T.any(DSL::Version, String)), caskroom_path: Pathname).returns(Pathname) } def metadata_versioned_path(version: self.version, caskroom_path: self.caskroom_path) cask_version = (version || :unknown).to_s raise CaskError, "Cannot create metadata path with empty version." if cask_version.empty? metadata_main_container_path(caskroom_path:).join(cask_version) end sig { params( version: T.nilable(T.any(DSL::Version, String)), timestamp: T.any(Symbol, String), create: T::Boolean, caskroom_path: Pathname, ).returns(T.nilable(Pathname)) } def metadata_timestamped_path(version: self.version, timestamp: :latest, create: false, caskroom_path: self.caskroom_path) case timestamp when :latest raise CaskError, "Cannot create metadata path when timestamp is :latest." if create return Pathname.glob(metadata_versioned_path(version:, caskroom_path:).join("*")).max when :now timestamp = new_timestamp when Symbol raise CaskError, "Invalid timestamp symbol :#{timestamp}. Valid symbols are :latest and :now." end path = metadata_versioned_path(version:, caskroom_path:).join(timestamp) if create && !path.directory? odebug "Creating metadata directory: #{path}" path.mkpath end path end sig { params( leaf: String, version: T.nilable(T.any(DSL::Version, String)), timestamp: T.any(Symbol, String), create: T::Boolean, caskroom_path: Pathname, ).returns(T.nilable(Pathname)) } def metadata_subdir(leaf, version: self.version, timestamp: :latest, create: false, caskroom_path: self.caskroom_path) raise CaskError, "Cannot create metadata subdir when timestamp is :latest." if create && timestamp == :latest raise CaskError, "Cannot create metadata subdir for empty leaf." if !leaf.respond_to?(:empty?) || leaf.empty? parent = metadata_timestamped_path(version:, timestamp:, create:, caskroom_path:) return if parent.nil? subdir = parent.join(leaf) if create && !subdir.directory? odebug "Creating metadata subdirectory: #{subdir}" subdir.mkpath end subdir end private sig { params(time: Time).returns(String) } def new_timestamp(time = Time.now) time.utc.strftime(TIMESTAMP_FORMAT) end end 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/depends_on.rb
Library/Homebrew/cask/dsl/depends_on.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "delegate" require "requirements/macos_requirement" module Cask class DSL # Class corresponding to the `depends_on` stanza. class DependsOn < SimpleDelegator VALID_KEYS = Set.new([ :formula, :cask, :macos, :arch, ]).freeze VALID_ARCHES = { intel: { type: :intel, bits: 64 }, # specific x86_64: { type: :intel, bits: 64 }, arm64: { type: :arm, bits: 64 }, }.freeze attr_reader :arch, :cask, :formula, :macos def initialize super({}) @cask ||= [] @formula ||= [] end def load(**pairs) pairs.each do |key, value| raise "invalid depends_on key: '#{key.inspect}'" unless VALID_KEYS.include?(key) __getobj__[key] = send(:"#{key}=", *value) end end def formula=(*args) @formula.concat(args) end def cask=(*args) @cask.concat(args) end sig { params(args: T.any(String, Symbol)).returns(T.nilable(MacOSRequirement)) } def macos=(*args) raise "Only a single 'depends_on macos' is allowed." if defined?(@macos) # workaround for https://github.com/sorbet/sorbet/issues/6860 first_arg = args.first first_arg_s = first_arg&.to_s begin @macos = if args.count > 1 MacOSRequirement.new([args], comparator: "==") elsif first_arg.is_a?(Symbol) && MacOSVersion::SYMBOLS.key?(first_arg) MacOSRequirement.new([args.first], comparator: "==") elsif (md = /^\s*(?<comparator><|>|[=<>]=)\s*:(?<version>\S+)\s*$/.match(first_arg_s)) MacOSRequirement.new([T.must(md[:version]).to_sym], comparator: md[:comparator]) elsif (md = /^\s*(?<comparator><|>|[=<>]=)\s*(?<version>\S+)\s*$/.match(first_arg_s)) MacOSRequirement.new([md[:version]], comparator: md[:comparator]) # This is not duplicate of the first case: see `args.first` and a different comparator. else # rubocop:disable Lint/DuplicateBranch MacOSRequirement.new([args.first], comparator: "==") end rescue MacOSVersion::Error, TypeError => e raise "invalid 'depends_on macos' value: #{e}" end end def arch=(*args) @arch ||= [] arches = args.map do |elt| elt.to_s.downcase.sub(/^:/, "").tr("-", "_").to_sym end invalid_arches = arches - VALID_ARCHES.keys raise "invalid 'depends_on arch' values: #{invalid_arches.inspect}" unless invalid_arches.empty? @arch.concat(arches.map { |arch| VALID_ARCHES[arch] }) end sig { returns(T::Boolean) } def empty? = T.let(__getobj__, T::Hash[Symbol, T.untyped]).empty? sig { returns(T::Boolean) } def present? = !empty? end end 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/version.rb
Library/Homebrew/cask/dsl/version.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true module Cask class DSL # Class corresponding to the `version` stanza. class Version < ::String DIVIDERS = { "." => :dots, "-" => :hyphens, "_" => :underscores, }.freeze DIVIDER_REGEX = /(#{DIVIDERS.keys.map { |v| Regexp.quote(v) }.join("|")})/ MAJOR_MINOR_PATCH_REGEX = /^([^.,:]+)(?:.([^.,:]+)(?:.([^.,:]+))?)?/ INVALID_CHARACTERS = /[^0-9a-zA-Z.,:\-_+ ]/ class << self private def define_divider_methods(divider) define_divider_deletion_method(divider) define_divider_conversion_methods(divider) end def define_divider_deletion_method(divider) method_name = deletion_method_name(divider) define_method(method_name) do T.bind(self, Version) version { delete(divider) } end end def deletion_method_name(divider) "no_#{DIVIDERS[divider]}" end def define_divider_conversion_methods(left_divider) (DIVIDERS.keys - [left_divider]).each do |right_divider| define_divider_conversion_method(left_divider, right_divider) end end def define_divider_conversion_method(left_divider, right_divider) method_name = conversion_method_name(left_divider, right_divider) define_method(method_name) do T.bind(self, Version) version { gsub(left_divider, right_divider) } end end def conversion_method_name(left_divider, right_divider) "#{DIVIDERS[left_divider]}_to_#{DIVIDERS[right_divider]}" end end DIVIDERS.each_key do |divider| define_divider_methods(divider) end attr_reader :raw_version sig { params(raw_version: T.nilable(T.any(String, Symbol))).void } def initialize(raw_version) @raw_version = raw_version super(raw_version.to_s) invalid = invalid_characters raise TypeError, "#{raw_version} contains invalid characters: #{invalid.uniq.join}!" if invalid.present? end def invalid_characters return [] if raw_version.blank? || latest? raw_version.scan(INVALID_CHARACTERS) end sig { returns(T::Boolean) } def unstable? return false if latest? s = downcase.delete(".").gsub(/[^a-z\d]+/, "-") return true if s.match?(/(\d+|\b)(alpha|beta|preview|rc|dev|canary|snapshot)(\d+|\b)/i) return true if s.match?(/\A[a-z\d]+(-\d+)*-?(a|b|pre)(\d+|\b)/i) false end sig { returns(T::Boolean) } def latest? to_s == "latest" end # The major version. # # @api public sig { returns(T.self_type) } def major version { slice(MAJOR_MINOR_PATCH_REGEX, 1) } end # The minor version. # # @api public sig { returns(T.self_type) } def minor version { slice(MAJOR_MINOR_PATCH_REGEX, 2) } end # The patch version. # # @api public sig { returns(T.self_type) } def patch version { slice(MAJOR_MINOR_PATCH_REGEX, 3) } end # The major and minor version. # # @api public sig { returns(T.self_type) } def major_minor version { [major, minor].reject(&:empty?).join(".") } end # The major, minor and patch version. # # @api public sig { returns(T.self_type) } def major_minor_patch version { [major, minor, patch].reject(&:empty?).join(".") } end # The minor and patch version. # # @api public sig { returns(T.self_type) } def minor_patch version { [minor, patch].reject(&:empty?).join(".") } end # The comma separated values of the version as array. # # @api public sig { returns(T::Array[Version]) } # Only top-level T.self_type is supported https://sorbet.org/docs/self-type def csv split(",").map { self.class.new(it) } end # The version part before the first comma. # # @api public sig { returns(T.self_type) } def before_comma version { split(",", 2).first } end # The version part after the first comma. # # @api public sig { returns(T.self_type) } def after_comma version { split(",", 2).second } end # The version without any dividers. # # @see DIVIDER_REGEX # @api public sig { returns(T.self_type) } def no_dividers version { gsub(DIVIDER_REGEX, "") } end # The version with the given record separator removed from the end. # # @see String#chomp # @api public sig { params(separator: String).returns(T.self_type) } def chomp(separator = T.unsafe(nil)) version { to_s.chomp(separator) } end private sig { returns(T.self_type) } def version return self if empty? || latest? self.class.new(yield) 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/dsl/rename.rb
Library/Homebrew/cask/dsl/rename.rb
# typed: strict # frozen_string_literal: true module Cask class DSL # Class corresponding to the `rename` stanza. class Rename sig { returns(String) } attr_reader :from, :to sig { params(from: String, to: String).void } def initialize(from, to) @from = from @to = to end sig { params(staged_path: Pathname).void } def perform_rename(staged_path) return unless staged_path.exist? # Find files matching the glob pattern matching_files = if @from.include?("*") staged_path.glob(@from) else [staged_path.join(@from)].select(&:exist?) end return if matching_files.empty? # Rename the first matching file to the target path source_file = matching_files.first return if source_file.nil? target_file = staged_path.join(@to) # Ensure target directory exists target_file.dirname.mkpath # Perform the rename source_file.rename(target_file.to_s) if source_file.exist? end sig { returns(T::Hash[Symbol, String]) } def pairs { from:, to: } end sig { returns(String) } def to_s = pairs.inspect end end 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/uninstall_preflight.rb
Library/Homebrew/cask/dsl/uninstall_preflight.rb
# typed: strict # frozen_string_literal: true require "cask/staged" module Cask class DSL # Class corresponding to the `uninstall_preflight` stanza. class UninstallPreflight < Base include Staged end end 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/caveats.rb
Library/Homebrew/cask/dsl/caveats.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true module Cask class DSL # Class corresponding to the `caveats` stanza. # # Each method should handle output, following the # convention of at least one trailing blank line so that the user # can distinguish separate caveats. # # The return value of the last method in the block is also sent # to the output by the caller, but that feature is only for the # convenience of cask authors. class Caveats < Base sig { params(args: T.anything).void } def initialize(*args) super @built_in_caveats = T.let({}, T::Hash[Symbol, String]) @custom_caveats = T.let([], T::Array[String]) @discontinued = T.let(false, T::Boolean) end def self.caveat(name, &block) define_method(name) do |*args| key = [name, *args] text = instance_exec(*args, &block) @built_in_caveats[key] = text if text :built_in_caveat end end private_class_method :caveat sig { returns(T::Boolean) } def discontinued? = @discontinued sig { returns(String) } def to_s (@custom_caveats + @built_in_caveats.values).join("\n") end # Override `puts` to collect caveats. sig { params(args: String).returns(Symbol) } def puts(*args) @custom_caveats += args :built_in_caveat end sig { params(block: T.proc.returns(T.nilable(T.any(Symbol, String)))).void } def eval_caveats(&block) result = instance_eval(&block) return unless result return if result == :built_in_caveat @custom_caveats << result.to_s.sub(/\s*\Z/, "\n") end caveat :kext do next if MacOS.version < :sonoma navigation_path = if MacOS.version >= :ventura "System Settings → Privacy & Security" else "System Preferences → Security & Privacy → General" end <<~EOS #{@cask} requires a kernel extension to work. If the installation fails, retry after you enable it in: #{navigation_path} For more information, refer to vendor documentation or this Apple Technical Note: #{Formatter.url("https://developer.apple.com/library/content/technotes/tn2459/_index.html")} EOS end caveat :unsigned_accessibility do |access = "Accessibility"| # access: the category in the privacy settings the app requires. navigation_path = if MacOS.version >= :ventura "System Settings → Privacy & Security" else "System Preferences → Security & Privacy → Privacy" end <<~EOS #{@cask} is not signed and requires Accessibility access, so you will need to re-grant Accessibility access every time the app is updated. Enable or re-enable it in: #{navigation_path} → #{access} To re-enable, untick and retick #{@cask}.app. EOS end caveat :path_environment_variable do |path| <<~EOS To use #{@cask}, you may need to add the #{path} directory to your PATH environment variable, e.g. (for Bash shell): export PATH=#{path}:"$PATH" EOS end caveat :zsh_path_helper do |path| <<~EOS To use #{@cask}, zsh users may need to add the following line to their ~/.zprofile. (Among other effects, #{path} will be added to the PATH environment variable): eval `/usr/libexec/path_helper -s` EOS end caveat :files_in_usr_local do next unless HOMEBREW_PREFIX.to_s.downcase.start_with?("/usr/local") <<~EOS Cask #{@cask} installs files under /usr/local. The presence of such files can cause warnings when running `brew doctor`, which is considered to be a bug in Homebrew Cask. EOS end caveat :depends_on_java do |java_version = :any| if java_version == :any <<~EOS #{@cask} requires Java. You can install the latest version with: brew install --cask temurin EOS elsif java_version.include?("+") <<~EOS #{@cask} requires Java #{java_version}. You can install the latest version with: brew install --cask temurin EOS else <<~EOS #{@cask} requires Java #{java_version}. You can install it with: brew install --cask temurin@#{java_version} EOS end end caveat :requires_rosetta do next if Homebrew::SimulateSystem.current_arch != :arm <<~EOS #{@cask} is built for Intel macOS and so requires Rosetta 2 to be installed. You can install Rosetta 2 with: softwareupdate --install-rosetta --agree-to-license Note that it is very difficult to remove Rosetta 2 once it is installed. EOS end caveat :logout do <<~EOS You must log out and log back in for the installation of #{@cask} to take effect. EOS end caveat :reboot do <<~EOS You must reboot for the installation of #{@cask} to take effect. EOS end caveat :license do |web_page| <<~EOS Installing #{@cask} means you have AGREED to the license at: #{Formatter.url(web_page.to_s)} EOS end caveat :free_license do |web_page| <<~EOS The vendor offers a free license for #{@cask} at: #{Formatter.url(web_page.to_s)} 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/cask/dsl/base.rb
Library/Homebrew/cask/dsl/base.rb
# typed: strict # frozen_string_literal: true require "cask/utils" require "on_system" module Cask class DSL # Superclass for all stanzas which take a block. class Base extend Forwardable sig { returns(Cask) } attr_reader :cask sig { returns(T.class_of(SystemCommand)) } attr_reader :command sig { params(cask: Cask, command: T.class_of(SystemCommand)).void } def initialize(cask, command = SystemCommand) @cask = cask @command = T.let(command, T.class_of(SystemCommand)) end def_delegators :@cask, :token, :version, :caskroom_path, :staged_path, :appdir, :language, :arch sig { params(executable: String, options: T.untyped).returns(T.nilable(SystemCommand::Result)) } def system_command(executable, **options) @command.run!(executable, **options) end # No need to define it as it's the default/superclass implementation. # rubocop:disable Style/MissingRespondToMissing sig { params(method: T.nilable(Symbol), args: T.untyped).returns(T.nilable(Object)) } def method_missing(method, *args) if method underscored_class = T.must(self.class.name).gsub(/([[:lower:]])([[:upper:]][[:lower:]])/, '\1_\2').downcase section = underscored_class.split("::").last Utils.method_missing_message(method, @cask.to_s, section) nil else super end end # rubocop:enable Style/MissingRespondToMissing end end 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/postflight.rb
Library/Homebrew/cask/dsl/postflight.rb
# typed: strict # frozen_string_literal: true require "cask/staged" module Cask class DSL # Class corresponding to the `postflight` stanza. class Postflight < Base include Staged end end 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/conflicts_with.rb
Library/Homebrew/cask/dsl/conflicts_with.rb
# typed: strict # frozen_string_literal: true require "delegate" require "extend/hash/keys" require "utils/output" module Cask class DSL # Class corresponding to the `conflicts_with` stanza. class ConflictsWith < SimpleDelegator VALID_KEYS = [:cask].freeze ODISABLED_KEYS = [ :formula, :macos, :arch, :x11, :java, ].freeze sig { params(options: T.anything).void } def initialize(**options) options.assert_valid_keys(*VALID_KEYS, *ODISABLED_KEYS) options.keys.intersection(ODISABLED_KEYS).each do |key| ::Utils::Output.odisabled "conflicts_with #{key}:" end conflicts = options.transform_values { |v| Set.new(Kernel.Array(v)) } conflicts.default = Set.new super(conflicts) end sig { params(generator: T.anything).returns(String) } def to_json(generator) __getobj__.transform_values(&:to_a).to_json(generator) 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/dsl/preflight.rb
Library/Homebrew/cask/dsl/preflight.rb
# typed: strict # frozen_string_literal: true require "cask/staged" module Cask class DSL # Class corresponding to the `preflight` stanza. class Preflight < Base include Staged end end 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/uninstall_postflight.rb
Library/Homebrew/cask/dsl/uninstall_postflight.rb
# typed: strict # frozen_string_literal: true module Cask class DSL # Class corresponding to the `uninstall_postflight` stanza. class UninstallPostflight < Base end end 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/container.rb
Library/Homebrew/cask/dsl/container.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "unpack_strategy" module Cask class DSL # Class corresponding to the `container` stanza. class Container attr_accessor :nested, :type def initialize(nested: nil, type: nil) @nested = nested @type = type return if type.nil? return unless UnpackStrategy.from_type(type).nil? raise "invalid container type: #{type.inspect}" end def pairs instance_variables.to_h { |ivar| [ivar[1..].to_sym, instance_variable_get(ivar)] }.compact end def to_yaml pairs.to_yaml end sig { returns(String) } def to_s = pairs.inspect end end 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/vst_plugin.rb
Library/Homebrew/cask/artifact/vst_plugin.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `vst_plugin` stanza. class VstPlugin < Moved sig { returns(String) } def self.english_name "VST Plugin" 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/artifact/keyboard_layout.rb
Library/Homebrew/cask/artifact/keyboard_layout.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `keyboard_layout` stanza. class KeyboardLayout < Moved def install_phase(**options) super delete_keyboard_layout_cache(**options) end def uninstall_phase(**options) super delete_keyboard_layout_cache(**options) end private def delete_keyboard_layout_cache(command: nil, **_) command.run!( "/bin/rm", args: ["-f", "--", "/System/Library/Caches/com.apple.IntlDataCache.le*"], sudo: true, sudo_as_root: 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/cask/artifact/binary.rb
Library/Homebrew/cask/artifact/binary.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/symlinked" module Cask module Artifact # Artifact corresponding to the `binary` stanza. class Binary < Symlinked def link(command: nil, **options) super return if source.executable? if source.writable? FileUtils.chmod "+x", source else command.run!("chmod", args: ["+x", source], sudo: true) end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/artifact/symlinked.rb
Library/Homebrew/cask/artifact/symlinked.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/relocated" module Cask module Artifact # Superclass for all artifacts which are installed by symlinking them to the target location. class Symlinked < Relocated sig { returns(String) } def self.link_type_english_name "Symlink" end sig { returns(String) } def self.english_description "#{english_name} #{link_type_english_name}s" end def install_phase(**options) link(**options) end def uninstall_phase(**options) unlink(**options) end def summarize_installed if target.symlink? && target.exist? && target.readlink.exist? "#{printable_target} -> #{target.readlink} (#{target.readlink.abv})" else string = if target.symlink? "#{printable_target} -> #{target.readlink}" else printable_target end Formatter.error(string, label: "Broken Link") end end private def link(force: false, adopt: false, command: nil, **_options) unless source.exist? raise CaskError, "It seems the #{self.class.link_type_english_name.downcase} " \ "source '#{source}' is not there." end if target.exist? message = "It seems there is already #{self.class.english_article} " \ "#{self.class.english_name} at '#{target}'" if (force || adopt) && target.symlink? && (target.realpath == source.realpath || target.realpath.to_s.start_with?("#{cask.caskroom_path}/")) opoo "#{message}; overwriting." Utils.gain_permissions_remove(target, command:) elsif (formula = conflicting_formula) opoo "#{message} from formula #{formula}; skipping link." return else raise CaskError, "#{message}." end end ohai "Linking #{self.class.english_name} '#{source.basename}' to '#{target}'" create_filesystem_link(command) end def unlink(command: nil, **) return unless target.symlink? ohai "Unlinking #{self.class.english_name} '#{target}'" if (formula = conflicting_formula) odebug "#{target} is from formula #{formula}; skipping unlink." return end Utils.gain_permissions_remove(target, command:) end sig { params(command: T.class_of(SystemCommand)).void } def create_filesystem_link(command) Utils.gain_permissions_mkpath(target.dirname, command:) command.run! "/bin/ln", args: ["--no-dereference", "--force", "--symbolic", source, target], sudo: !target.dirname.writable? end # Check if the target file is a symlink that originates from a formula # with the same name as this cask, indicating a potential conflict sig { returns(T.nilable(String)) } def conflicting_formula if target.symlink? && target.exist? && (match = target.realpath.to_s.match(%r{^#{HOMEBREW_CELLAR}/(?<formula>[^/]+)/}o)) match[:formula] end rescue => e # If we can't determine the realpath or any other error occurs, # don't treat it as a conflicting formula file odebug "Error checking for conflicting formula file: #{e}" nil end end end end require "extend/os/cask/artifact/symlinked"
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/abstract_uninstall.rb
Library/Homebrew/cask/artifact/abstract_uninstall.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "timeout" require "utils/user" require "cask/artifact/abstract_artifact" require "cask/pkg" require "extend/hash/keys" require "system_command" module Cask module Artifact # Abstract superclass for uninstall artifacts. class AbstractUninstall < AbstractArtifact include SystemCommand::Mixin ORDERED_DIRECTIVES = [ :early_script, :launchctl, :quit, :signal, :login_item, :kext, :script, :pkgutil, :delete, :trash, :rmdir, ].freeze METADATA_KEYS = [ :on_upgrade, ].freeze def self.from_args(cask, **directives) new(cask, **directives) end attr_reader :directives def initialize(cask, **directives) directives.assert_valid_keys(*ORDERED_DIRECTIVES, *METADATA_KEYS) super directives[:signal] = Array(directives[:signal]).flatten.each_slice(2).to_a @directives = directives # This is already included when loading from the API. return if cask.loaded_from_api? return unless directives.key?(:kext) cask.caveats do T.bind(self, ::Cask::DSL::Caveats) kext end end def to_h directives.to_h end sig { override.returns(String) } def summarize to_h.flat_map { |key, val| Array(val).map { |v| "#{key.inspect} => #{v.inspect}" } }.join(", ") end private def dispatch_uninstall_directives(**options) ORDERED_DIRECTIVES.each do |directive_sym| dispatch_uninstall_directive(directive_sym, **options) end end def dispatch_uninstall_directive(directive_sym, **options) return unless directives.key?(directive_sym) args = directives[directive_sym] send(:"uninstall_#{directive_sym}", *(args.is_a?(Hash) ? [args] : args), **options) end def stanza self.class.dsl_key end # Preserve prior functionality of script which runs first. Should rarely be needed. # :early_script should not delete files, better defer that to :script. # If cask writers never need :early_script it may be removed in the future. def uninstall_early_script(directives, **options) uninstall_script(directives, directive_name: :early_script, **options) end # :launchctl must come before :quit/:signal for cases where app would instantly re-launch def uninstall_launchctl(*services, command: nil, **_) booleans = [false, true] all_services = [] # if launchctl item contains a wildcard, find matching process(es) services.each do |service| all_services << service unless service.include?("*") next unless service.include?("*") found_services = find_launchctl_with_wildcard(service) next if found_services.blank? found_services.each { |found_service| all_services << found_service } end all_services.each do |service| ohai "Removing launchctl service #{service}" booleans.each do |sudo| plist_status = command.run( "/bin/launchctl", args: ["list", service], sudo:, sudo_as_root: sudo, print_stderr: false, ).stdout if plist_status.start_with?("{") result = command.run( "/bin/launchctl", args: ["remove", service], must_succeed: false, sudo:, sudo_as_root: sudo, ) next unless result.success? sleep 1 end paths = [ "/Library/LaunchAgents/#{service}.plist", "/Library/LaunchDaemons/#{service}.plist", ] paths.each { |elt| elt.prepend(Dir.home).freeze } unless sudo paths = paths.map { |elt| Pathname(elt) }.select(&:exist?) paths.each do |path| command.run("/bin/rm", args: ["-f", "--", path], must_succeed: false, sudo:, sudo_as_root: sudo) end # undocumented and untested: pass a path to uninstall :launchctl next unless Pathname(service).exist? command.run( "/bin/launchctl", args: ["unload", "-w", "--", service], must_succeed: false, sudo:, sudo_as_root: sudo, ) command.run( "/bin/rm", args: ["-f", "--", service], must_succeed: false, sudo:, sudo_as_root: sudo, ) sleep 1 end end end def running_processes(bundle_id) system_command!("/bin/launchctl", args: ["list"]) .stdout.lines.drop(1) .map { |line| line.chomp.split("\t") } .map { |pid, state, id| [pid.to_i, state.to_i, id] } .select do |(pid, _, id)| pid.nonzero? && /\A(?:application\.)?#{Regexp.escape(bundle_id)}(?:\.\d+){0,2}\Z/.match?(id) end end def find_launchctl_with_wildcard(search) regex = Regexp.escape(search).gsub("\\*", ".*") system_command!("/bin/launchctl", args: ["list"]) .stdout.lines.drop(1) # skip stdout column headers .filter_map do |line| pid, _state, id = line.chomp.split(/\s+/) id if pid.to_i.nonzero? && T.must(id).match?(regex) end end sig { returns(String) } def automation_access_instructions navigation_path = if MacOS.version >= :ventura "System Settings → Privacy & Security" else "System Preferences → Security & Privacy → Privacy" end <<~EOS Enable Automation access for "Terminal → System Events" in: #{navigation_path} → Automation if you haven't already. EOS end # :quit/:signal must come before :kext so the kext will not be in use by a running process def uninstall_quit(*bundle_ids, command: nil, **_) bundle_ids.each do |bundle_id| next unless running?(bundle_id) unless T.must(User.current).gui? opoo "Not logged into a GUI; skipping quitting application ID '#{bundle_id}'." next end ohai "Quitting application '#{bundle_id}'..." begin Timeout.timeout(10) do Kernel.loop do next unless quit(bundle_id).success? next if running?(bundle_id) puts "Application '#{bundle_id}' quit successfully." break end end rescue Timeout::Error opoo "Application '#{bundle_id}' did not quit. #{automation_access_instructions}" end end end def running?(bundle_id) script = <<~JAVASCRIPT 'use strict'; ObjC.import('stdlib') function run(argv) { try { var app = Application(argv[0]) if (app.running()) { $.exit(0) } } catch (err) { } $.exit(1) } JAVASCRIPT system_command("osascript", args: ["-l", "JavaScript", "-e", script, bundle_id], print_stderr: true).status.success? end def quit(bundle_id) script = <<~JAVASCRIPT 'use strict'; ObjC.import('stdlib') function run(argv) { var app = Application(argv[0]) try { app.quit() } catch (err) { if (app.running()) { $.exit(1) } } $.exit(0) } JAVASCRIPT system_command "osascript", args: ["-l", "JavaScript", "-e", script, bundle_id], print_stderr: false end private :quit # :signal should come after :quit so it can be used as a backup when :quit fails def uninstall_signal(*signals, command: nil, **_) signals.each do |pair| raise CaskInvalidError.new(cask, "Each #{stanza} :signal must consist of 2 elements.") if pair.size != 2 signal, bundle_id = pair ohai "Signalling '#{signal}' to application ID '#{bundle_id}'" pids = running_processes(bundle_id).map(&:first) next if pids.none? # Note that unlike :quit, signals are sent from the current user (not # upgraded to the superuser). This is a todo item for the future, but # there should be some additional thought/safety checks about that, as a # misapplied "kill" by root could bring down the system. The fact that we # learned the pid from AppleScript is already some degree of protection, # though indirect. # TODO: check the user that owns the PID and don't try to kill those from other users. odebug "Unix ids are #{pids.inspect} for processes with bundle identifier #{bundle_id}" begin Process.kill(signal, *pids) rescue Errno::EPERM => e opoo "Failed to kill #{bundle_id} PIDs #{pids.join(", ")} with signal #{signal}: #{e}" end sleep 3 end end def uninstall_login_item(*login_items, command: nil, successor: nil, **_) return if successor apps = cask.artifacts.select { |a| a.class.dsl_key == :app } derived_login_items = apps.map { |a| { path: a.target } } [*derived_login_items, *login_items].each do |item| type, id = if item.respond_to?(:key) && item.key?(:path) ["path", item[:path]] else ["name", item] end ohai "Removing login item #{id}" result = system_command( "osascript", args: [ "-e", %Q(tell application "System Events" to delete every login item whose #{type} is #{id.to_s.inspect}), ], ) opoo "Removal of login item #{id} failed. #{automation_access_instructions}" unless result.success? sleep 1 end end # :kext should be unloaded before attempting to delete the relevant file def uninstall_kext(*kexts, command: nil, **_) kexts.each do |kext| ohai "Unloading kernel extension #{kext}" is_loaded = system_command!( "/usr/sbin/kextstat", args: ["-l", "-b", kext], sudo: true, sudo_as_root: true, ).stdout if is_loaded.length > 1 system_command!( "/sbin/kextunload", args: ["-b", kext], sudo: true, sudo_as_root: true, ) sleep 1 end found_kexts = system_command!( "/usr/sbin/kextfind", args: ["-b", kext], sudo: true, sudo_as_root: true, ).stdout.chomp.lines found_kexts.each do |kext_path| ohai "Removing kernel extension #{kext_path}" system_command!( "/bin/rm", args: ["-rf", kext_path], sudo: true, sudo_as_root: true, ) end end end # :script must come before :pkgutil, :delete, or :trash so that the script file is not already deleted def uninstall_script(directives, directive_name: :script, force: false, command: nil, **_) # TODO: Create a common `Script` class to run this and Artifact::Installer. executable, script_arguments = self.class.read_script_arguments(directives, "uninstall", { must_succeed: true, sudo: false }, { print_stdout: true }, directive_name) ohai "Running uninstall script #{executable}" raise CaskInvalidError.new(cask, "#{stanza} :#{directive_name} without :executable.") if executable.nil? executable_path = staged_path_join_executable(executable) if (executable_path.absolute? && !executable_path.exist?) || (!executable_path.absolute? && which(executable_path.to_s).nil?) message = "uninstall script #{executable} does not exist" raise CaskError, "#{message}." unless force opoo "#{message}; skipping." return end command.run(executable_path, **script_arguments) sleep 1 end def uninstall_pkgutil(*pkgs, command: nil, **_) ohai "Uninstalling packages with `sudo` (which may request your password)..." pkgs.each do |regex| ::Cask::Pkg.all_matching(regex, command).each do |pkg| puts pkg.package_id pkg.uninstall end end end def each_resolved_path(action, paths) return enum_for(:each_resolved_path, action, paths) unless block_given? paths.each do |path| resolved_path = Pathname.new(path) resolved_path = resolved_path.expand_path if path.to_s.start_with?("~") if resolved_path.relative? || resolved_path.split.any? { |part| part.to_s == ".." } opoo "Skipping #{Formatter.identifier(action)} for relative path '#{path}'." next end if undeletable?(resolved_path) opoo "Skipping #{Formatter.identifier(action)} for undeletable path '#{path}'." next end begin yield path, Pathname.glob(resolved_path) rescue Errno::EPERM raise if File.readable?(File.expand_path("~/Library/Application Support/com.apple.TCC")) navigation_path = if MacOS.version >= :ventura "System Settings → Privacy & Security" else "System Preferences → Security & Privacy → Privacy" end odie "Unable to remove some files. Please enable Full Disk Access for your terminal under " \ "#{navigation_path} → Full Disk Access." end end end def uninstall_delete(*paths, command: nil, **_) return if paths.empty? ohai "Removing files:" each_resolved_path(:delete, paths) do |path, resolved_paths| puts path command.run!( "/usr/bin/xargs", args: ["-0", "--", "/bin/rm", "-r", "-f", "--"], input: resolved_paths.join("\0"), sudo: true, ) end end def uninstall_trash(*paths, **options) return if paths.empty? resolved_paths = each_resolved_path(:trash, paths).to_a ohai "Trashing files:", resolved_paths.map(&:first) trash_paths(*resolved_paths.flat_map(&:last), **options) end def trash_paths(*paths, command: nil, **_) return if paths.empty? stdout = system_command(HOMEBREW_LIBRARY_PATH/"cask/utils/trash.swift", args: paths, print_stderr: Homebrew::EnvConfig.developer?).stdout trashed, _, untrashable = stdout.partition("\n") trashed = trashed.split(":") untrashable = untrashable.split(":") trashed_with_permissions, untrashable = untrashable.partition do |path| Utils.gain_permissions(Pathname(path), ["-R"], SystemCommand) do system_command! HOMEBREW_LIBRARY_PATH/"cask/utils/trash.swift", args: [path], print_stderr: Homebrew::EnvConfig.developer? end true rescue false end trashed += trashed_with_permissions return trashed, untrashable if untrashable.empty? opoo "The following files could not be trashed, please do so manually:" $stderr.puts untrashable [trashed, untrashable] end def all_dirs?(*directories) directories.all?(&:directory?) end def recursive_rmdir(*directories, command: nil, **_) directories.all? do |resolved_path| puts resolved_path.sub(Dir.home, "~") if resolved_path.readable? children = resolved_path.children next false unless children.all? { |child| child.directory? || child.basename.to_s == ".DS_Store" } else lines = command.run!("/bin/ls", args: ["-A", "-F", "--", resolved_path], sudo: true, print_stderr: false) .stdout.lines.map(&:chomp) .flat_map(&:chomp) # Using `-F` above outputs directories ending with `/`. next false unless lines.all? { |l| l.end_with?("/") || l == ".DS_Store" } children = lines.map { |l| resolved_path/l.delete_suffix("/") } end # Directory counts as empty if it only contains a `.DS_Store`. if children.include?(ds_store = resolved_path/".DS_Store") Utils.gain_permissions_remove(ds_store, command:) children.delete(ds_store) end next false unless recursive_rmdir(*children, command:) Utils.gain_permissions_rmdir(resolved_path, command:) true end end def uninstall_rmdir(*directories, **kwargs) return if directories.empty? ohai "Removing directories if empty:" each_resolved_path(:rmdir, directories) do |_path, resolved_paths| next unless resolved_paths.all?(&:directory?) recursive_rmdir(*resolved_paths, **kwargs) end end sig { params(target: Pathname).returns(T::Boolean) } def undeletable?(target) !target.parent.writable? end end end end require "extend/os/cask/artifact/abstract_uninstall"
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/zap.rb
Library/Homebrew/cask/artifact/zap.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/abstract_uninstall" module Cask module Artifact # Artifact corresponding to the `zap` stanza. class Zap < AbstractUninstall sig { params(options: T.anything).void } def zap_phase(**options) dispatch_uninstall_directives(**options) 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/artifact/mdimporter.rb
Library/Homebrew/cask/artifact/mdimporter.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `mdimporter` stanza. class Mdimporter < Moved sig { returns(String) } def self.english_name "Spotlight metadata importer" end def install_phase(**options) super reload_spotlight(**options) end private def reload_spotlight(command: nil, **_) command.run!("/usr/bin/mdimport", args: ["-r", target]) 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/artifact/qlplugin.rb
Library/Homebrew/cask/artifact/qlplugin.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `qlplugin` stanza. class Qlplugin < Moved sig { returns(String) } def self.english_name "Quick Look Plugin" end def install_phase(**options) super reload_quicklook(**options) end def uninstall_phase(**options) super reload_quicklook(**options) end private def reload_quicklook(command: nil, **_) command.run!("/usr/bin/qlmanage", args: ["-r"]) 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/artifact/stage_only.rb
Library/Homebrew/cask/artifact/stage_only.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/abstract_artifact" module Cask module Artifact # Artifact corresponding to the `stage_only` stanza. class StageOnly < AbstractArtifact def self.from_args(cask, *args, **kwargs) if (args != [true] && args != ["true"]) || kwargs.present? raise CaskInvalidError.new(cask.token, "'stage_only' takes only a single argument: true") end new(cask, true) end sig { returns(T::Array[T::Boolean]) } def to_a [true] end sig { override.returns(String) } def summarize "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/cask/artifact/uninstall.rb
Library/Homebrew/cask/artifact/uninstall.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/abstract_uninstall" module Cask module Artifact # Artifact corresponding to the `uninstall` stanza. class Uninstall < AbstractUninstall UPGRADE_REINSTALL_SKIP_DIRECTIVES = [:quit, :signal].freeze def uninstall_phase(**options) upgrade = options.fetch(:upgrade, false) reinstall = options.fetch(:reinstall, false) raw_on_upgrade = directives[:on_upgrade] on_upgrade_syms = case raw_on_upgrade when Symbol [raw_on_upgrade] when Array raw_on_upgrade.map(&:to_sym) else [] end on_upgrade_set = on_upgrade_syms.to_set filtered_directives = ORDERED_DIRECTIVES.filter do |directive_sym| next false if directive_sym == :rmdir if (upgrade || reinstall) && UPGRADE_REINSTALL_SKIP_DIRECTIVES.include?(directive_sym) && on_upgrade_set.exclude?(directive_sym) next false end true end filtered_directives.each do |directive_sym| dispatch_uninstall_directive(directive_sym, **options) end end def post_uninstall_phase(**options) dispatch_uninstall_directive(:rmdir, **options) 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/artifact/font.rb
Library/Homebrew/cask/artifact/font.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `font` stanza. class Font < Moved end end 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/moved.rb
Library/Homebrew/cask/artifact/moved.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/relocated" require "cask/quarantine" module Cask module Artifact # Superclass for all artifacts that are installed by moving them to the target location. class Moved < Relocated sig { returns(String) } def self.english_description "#{english_name}s" end def install_phase(**options) move(**options) end def uninstall_phase(**options) move_back(**options) end def summarize_installed if target.exist? "#{printable_target} (#{target.abv})" else Formatter.error(printable_target, label: "Missing #{self.class.english_name}") end end private def move(adopt: false, auto_updates: false, force: false, verbose: false, predecessor: nil, reinstall: false, command: nil, **options) unless source.exist? raise CaskError, "It seems the #{self.class.english_name} source '#{source}' is not there." end if Utils.path_occupied?(target) if target.directory? && target.children.empty? && matching_artifact?(predecessor) # An upgrade removed the directory contents but left the directory itself (see below). unless source.directory? if target.parent.writable? && !force target.rmdir else Utils.gain_permissions_remove(target, command:) end end else if adopt ohai "Adopting existing #{self.class.english_name} at '#{target}'" unless auto_updates source_plist = Pathname("#{source}/Contents/Info.plist") target_plist = Pathname("#{target}/Contents/Info.plist") same = if source_plist.size? && (source_bundle_version = Homebrew::BundleVersion.from_info_plist(source_plist)) && target_plist.size? && (target_bundle_version = Homebrew::BundleVersion.from_info_plist(target_plist)) if source_bundle_version.short_version == target_bundle_version.short_version if source_bundle_version.version == target_bundle_version.version true else onoe "The bundle version of #{source} is #{source_bundle_version.version} but " \ "is #{target_bundle_version.version} for #{target}!" false end else onoe "The bundle short version of #{source} is #{source_bundle_version.short_version} but " \ "is #{target_bundle_version.short_version} for #{target}!" false end else command.run( "/usr/bin/diff", args: ["--recursive", "--brief", source, target], verbose:, print_stdout: verbose, ).success? end unless same raise CaskError, "It seems the existing #{self.class.english_name} is different from " \ "the one being installed." end end # Remove the source as we don't need to move it to the target location FileUtils.rm_r(source) return post_move(command) end message = "It seems there is already #{self.class.english_article} " \ "#{self.class.english_name} at '#{target}'" raise CaskError, "#{message}." if !force && !adopt opoo "#{message}; overwriting." delete(target, force:, command:, **options) end end ohai "Moving #{self.class.english_name} '#{source.basename}' to '#{target}'" Utils.gain_permissions_mkpath(target.dirname, command:) unless target.dirname.exist? if target.directory? && Quarantine.app_management_permissions_granted?(app: target, command:) if target.writable? source.children.each { |child| FileUtils.move(child, target/child.basename) } else command.run!("/bin/cp", args: ["-pR", *source.children, target], sudo: true) end Quarantine.copy_xattrs(source, target, command:) FileUtils.rm_r(source) elsif target.dirname.writable? FileUtils.move(source, target) else # default sudo user isn't necessarily able to write to Homebrew's locations # e.g. with runas_default set in the sudoers (5) file. command.run!("/bin/cp", args: ["-pR", source, target], sudo: true) FileUtils.rm_r(source) end post_move(command) end # Performs any actions necessary after the source has been moved to the target location. def post_move(command) FileUtils.ln_sf target, source add_altname_metadata(target, source.basename, command:) end def matching_artifact?(cask) return false unless cask cask.artifacts.any? do |a| a.instance_of?(self.class) && instance_of?(a.class) && a.target == target end end def move_back(skip: false, force: false, adopt: false, command: nil, **options) FileUtils.rm source if source.symlink? && source.dirname.join(source.readlink) == target if Utils.path_occupied?(source) message = "It seems there is already #{self.class.english_article} " \ "#{self.class.english_name} at '#{source}'" raise CaskError, "#{message}." if !force && !adopt opoo "#{message}; overwriting." delete(source, force:, command:, **options) end unless target.exist? return if skip || force raise CaskError, "It seems the #{self.class.english_name} source '#{target}' is not there." end ohai "Backing #{self.class.english_name} '#{target.basename}' up to '#{source}'" source.dirname.mkpath # We need to preserve extended attributes between copies. # This may fail and need sudo if the source has files with restricted permissions. [!source.parent.writable?, true].uniq.each do |sudo| result = command.run( "/bin/cp", args: ["-pR", target, source], must_succeed: sudo, sudo:, ) break if result.success? end delete(target, force:, command:, **options) end def delete(target, force: false, successor: nil, command: nil, **_) ohai "Removing #{self.class.english_name} '#{target}'" raise CaskError, "Cannot remove undeletable #{self.class.english_name}." if undeletable?(target) return unless Utils.path_occupied?(target) if target.directory? && matching_artifact?(successor) && Quarantine.app_management_permissions_granted?( app: target, command:, ) # If an app folder is deleted, macOS considers the app uninstalled and removes some data. # Remove only the contents to handle this case. target.children.each do |child| Utils.gain_permissions_remove(child, command:) end else Utils.gain_permissions_remove(target, command:) end end sig { params(target: Pathname).returns(T::Boolean) } def undeletable?(target) !target.parent.writable? end end end end require "extend/os/cask/artifact/moved"
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/abstract_flight_block.rb
Library/Homebrew/cask/artifact/abstract_flight_block.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/abstract_artifact" module Cask module Artifact # Abstract superclass for block artifacts. class AbstractFlightBlock < AbstractArtifact def self.dsl_key super.to_s.sub(/_block$/, "").to_sym end def self.uninstall_dsl_key :"uninstall_#{dsl_key}" end attr_reader :directives def initialize(cask, **directives) super(cask) @directives = directives end def install_phase(**) abstract_phase(self.class.dsl_key) end def uninstall_phase(**) abstract_phase(self.class.uninstall_dsl_key) end def summarize directives.keys.map(&:to_s).join(", ") end private def class_for_dsl_key(dsl_key) namespace = self.class.name.to_s.sub(/::.*::.*$/, "") self.class.const_get("#{namespace}::DSL::#{dsl_key.to_s.split("_").map(&:capitalize).join}") end def abstract_phase(dsl_key) return if (block = directives[dsl_key]).nil? class_for_dsl_key(dsl_key).new(cask).instance_eval(&block) 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/artifact/zshcompletion.rb
Library/Homebrew/cask/artifact/zshcompletion.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/shellcompletion" module Cask module Artifact # Artifact corresponding to the `zsh_completion` stanza. class ZshCompletion < ShellCompletion sig { params(target: T.any(String, Pathname)).returns(Pathname) } def resolve_target(target) name = if target.to_s.start_with? "_" target else new_name = "_#{File.basename(target, File.extname(target))}" odebug "Renaming completion #{target} to #{new_name}" new_name end config.zsh_completion/name end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/artifact/shellcompletion.rb
Library/Homebrew/cask/artifact/shellcompletion.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/symlinked" module Cask module Artifact class ShellCompletion < Symlinked sig { params(_: T.any(String, Pathname)).returns(Pathname) } def resolve_target(_) raise CaskInvalidError, "Shell completion without shell info" 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/artifact/audio_unit_plugin.rb
Library/Homebrew/cask/artifact/audio_unit_plugin.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `audio_unit_plugin` stanza. class AudioUnitPlugin < Moved end end 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/abstract_artifact.rb
Library/Homebrew/cask/artifact/abstract_artifact.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "extend/object/deep_dup" require "utils/output" module Cask module Artifact # Abstract superclass for all artifacts. class AbstractArtifact extend T::Helpers extend ::Utils::Output::Mixin abstract! include Comparable include ::Utils::Output::Mixin def self.english_name @english_name ||= T.must(name).sub(/^.*:/, "").gsub(/(.)([A-Z])/, '\1 \2') end def self.english_article @english_article ||= /^[aeiou]/i.match?(english_name) ? "an" : "a" end def self.dsl_key @dsl_key ||= T.must(name).sub(/^.*:/, "").gsub(/(.)([A-Z])/, '\1_\2').downcase.to_sym end def self.dirmethod @dirmethod ||= :"#{dsl_key}dir" end sig { abstract.returns(String) } def summarize; end def staged_path_join_executable(path) path = Pathname(path) path = path.expand_path if path.to_s.start_with?("~") absolute_path = if path.absolute? path else cask.staged_path.join(path) end FileUtils.chmod "+x", absolute_path if absolute_path.exist? && !absolute_path.executable? if absolute_path.exist? absolute_path else path end end def sort_order @sort_order ||= [ PreflightBlock, # The `uninstall` stanza should be run first, as it may # depend on other artifacts still being installed. Uninstall, Installer, # `pkg` should be run before `binary`, so # targets are created prior to linking. # `pkg` should be run before `app`, since an `app` could # contain a nested installer (e.g. `wireshark`). Pkg, [ App, Suite, Artifact, Colorpicker, Prefpane, Qlplugin, Mdimporter, Dictionary, Font, Service, InputMethod, InternetPlugin, KeyboardLayout, AudioUnitPlugin, VstPlugin, Vst3Plugin, ScreenSaver, ], Binary, Manpage, PostflightBlock, Zap, ].each_with_index.flat_map { |classes, i| Array(classes).map { |c| [c, i] } }.to_h end def <=>(other) return unless other.class < AbstractArtifact return 0 if instance_of?(other.class) (sort_order[self.class] <=> sort_order[other.class]).to_i end # TODO: this sort of logic would make more sense in dsl.rb, or a # constructor called from dsl.rb, so long as that isn't slow. def self.read_script_arguments(arguments, stanza, default_arguments = {}, override_arguments = {}, key = nil) # TODO: when stanza names are harmonized with class names, # stanza may not be needed as an explicit argument description = key ? "#{stanza} #{key.inspect}" : stanza.to_s # backward-compatible string value arguments = if arguments.is_a?(String) { executable: arguments } else # Avoid mutating the original argument arguments.dup end # key sanity permitted_keys = [:args, :input, :executable, :must_succeed, :sudo, :print_stdout, :print_stderr] unknown_keys = arguments.keys - permitted_keys unless unknown_keys.empty? opoo "Unknown arguments to #{description} -- " \ "#{unknown_keys.inspect} (ignored). Running " \ "`brew update; brew cleanup` will likely fix it." end arguments.select! { |k| permitted_keys.include?(k) } # key warnings override_keys = override_arguments.keys ignored_keys = arguments.keys & override_keys unless ignored_keys.empty? onoe "Some arguments to #{description} will be ignored -- :#{unknown_keys.inspect} (overridden)." end # extract executable executable = arguments.key?(:executable) ? arguments.delete(:executable) : nil arguments = default_arguments.merge arguments arguments.merge! override_arguments [executable, arguments] end attr_reader :cask def initialize(cask, *dsl_args) @cask = cask @dirmethod = nil @dsl_args = dsl_args.deep_dup @dsl_key = nil @english_article = nil @english_name = nil @sort_order = nil end def config cask.config end sig { returns(String) } def to_s "#{summarize} (#{self.class.english_name})" end def to_args @dsl_args.compact_blank 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/artifact/preflight_block.rb
Library/Homebrew/cask/artifact/preflight_block.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/abstract_flight_block" module Cask module Artifact # Artifact corresponding to the `preflight` stanza. class PreflightBlock < AbstractFlightBlock end end 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/bashcompletion.rb
Library/Homebrew/cask/artifact/bashcompletion.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/shellcompletion" module Cask module Artifact # Artifact corresponding to the `bash_completion` stanza. class BashCompletion < ShellCompletion sig { params(target: T.any(String, Pathname)).returns(Pathname) } def resolve_target(target) name = if File.extname(target).nil? target else new_name = File.basename(target, File.extname(target)) odebug "Renaming completion #{target} to #{new_name}" new_name end config.bash_completion/name end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/artifact/app.rb
Library/Homebrew/cask/artifact/app.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `app` stanza. class App < Moved sig { params( adopt: T::Boolean, auto_updates: T.nilable(T::Boolean), force: T::Boolean, verbose: T::Boolean, predecessor: T.nilable(Cask), successor: T.nilable(Cask), reinstall: T::Boolean, command: T.class_of(SystemCommand), ).void } def install_phase( adopt: false, auto_updates: false, force: false, verbose: false, predecessor: nil, successor: nil, reinstall: false, command: SystemCommand ) super return if target.ascend.none? { OS::Mac.system_dir?(it) } odebug "Fixing up '#{target}' permissions for installation to '#{target.parent}'" # Ensure that globally installed applications can be accessed by all users. # We shell out to `chmod` instead of using `FileUtils.chmod` so that using `+X` works correctly. command.run!("chmod", args: ["-R", "a+rX", target], sudo: !target.writable?) 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/artifact/manpage.rb
Library/Homebrew/cask/artifact/manpage.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/symlinked" module Cask module Artifact # Artifact corresponding to the `manpage` stanza. class Manpage < Symlinked attr_reader :section def self.from_args(cask, source) section = source.to_s[/\.([1-8]|n|l)(?:\.gz)?$/, 1] raise CaskInvalidError, "'#{source}' is not a valid man page name" unless section new(cask, source, section) end def initialize(cask, source, section) @section = section super(cask, source) end def resolve_target(target) config.manpagedir.join("man#{section}", target) 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/artifact/artifact.rb
Library/Homebrew/cask/artifact/artifact.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Generic artifact corresponding to the `artifact` stanza. class Artifact < Moved sig { returns(String) } def self.english_name "Generic Artifact" end sig { params(cask: Cask, args: T.untyped).returns(T.attached_class) } def self.from_args(cask, *args) source, options = args raise CaskInvalidError.new(cask.token, "No source provided for #{english_name}.") if source.blank? unless options&.key?(:target) raise CaskInvalidError.new(cask.token, "#{english_name} '#{source}' requires a target.") end new(cask, source, **options) end sig { params(target: T.any(String, Pathname)).returns(Pathname) } def resolve_target(target) super(target, base_dir: nil) 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/artifact/screen_saver.rb
Library/Homebrew/cask/artifact/screen_saver.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `screen_saver` stanza. class ScreenSaver < Moved end end 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/fishcompletion.rb
Library/Homebrew/cask/artifact/fishcompletion.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/shellcompletion" module Cask module Artifact # Artifact corresponding to the `fish_completion` stanza. class FishCompletion < ShellCompletion sig { params(target: T.any(String, Pathname)).returns(Pathname) } def resolve_target(target) name = if target.to_s.end_with? ".fish" target else new_name = "#{File.basename(target, File.extname(target))}.fish" odebug "Renaming completion #{target} to #{new_name}" new_name end config.fish_completion/name end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/artifact/dictionary.rb
Library/Homebrew/cask/artifact/dictionary.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `dictionary` stanza. class Dictionary < Moved end end 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/internet_plugin.rb
Library/Homebrew/cask/artifact/internet_plugin.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `internet_plugin` stanza. class InternetPlugin < Moved end end 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/installer.rb
Library/Homebrew/cask/artifact/installer.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/abstract_artifact" require "extend/hash/keys" module Cask module Artifact # Artifact corresponding to the `installer` stanza. class Installer < AbstractArtifact VALID_KEYS = Set.new([ :manual, :script, ]).freeze def install_phase(command: nil, **_) if manual_install puts <<~EOS Cask #{cask} only provides a manual installer. To run it and complete the installation: open #{cask.staged_path.join(path).to_s.shellescape} EOS else ohai "Running #{self.class.dsl_key} script '#{path}'" executable_path = staged_path_join_executable(path) command.run!( executable_path, **args, env: { "PATH" => PATH.new( HOMEBREW_PREFIX/"bin", HOMEBREW_PREFIX/"sbin", ENV.fetch("PATH") ) }, reset_uid: !args[:sudo], ) end end def self.from_args(cask, **args) raise CaskInvalidError.new(cask, "'installer' stanza requires an argument.") if args.empty? if args.key?(:script) && !args[:script].respond_to?(:key?) if args.key?(:executable) raise CaskInvalidError.new(cask, "'installer' stanza gave arguments for both :script and :executable.") end args[:executable] = args[:script] args.delete(:script) args = { script: args } end if args.keys.count != 1 raise CaskInvalidError.new( cask, "invalid 'installer' stanza: Only one of #{VALID_KEYS.inspect} is permitted.", ) end args.assert_valid_keys(*VALID_KEYS) new(cask, **args) end attr_reader :path, :args sig { returns(T::Boolean) } attr_reader :manual_install def initialize(cask, **args) super if args.key?(:manual) @path = Pathname(args[:manual]) @args = [] @manual_install = true else path, @args = self.class.read_script_arguments( args[:script], self.class.dsl_key.to_s, { must_succeed: true, sudo: false }, print_stdout: true ) raise CaskInvalidError.new(cask, "#{self.class.dsl_key} missing executable") if path.nil? @path = Pathname(path) @manual_install = false end end sig { override.returns(String) } def summarize = path.to_s def to_h { path: }.tap do |h| h[:args] = args unless manual_install 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/cask/artifact/input_method.rb
Library/Homebrew/cask/artifact/input_method.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `input_method` stanza. class InputMethod < Moved end end 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/prefpane.rb
Library/Homebrew/cask/artifact/prefpane.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `prefpane` stanza. class Prefpane < Moved sig { returns(String) } def self.english_name "Preference Pane" 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/artifact/postflight_block.rb
Library/Homebrew/cask/artifact/postflight_block.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/abstract_flight_block" module Cask module Artifact # Artifact corresponding to the `postflight` stanza. class PostflightBlock < AbstractFlightBlock end end 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/service.rb
Library/Homebrew/cask/artifact/service.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `service` stanza. class Service < Moved end end 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/pkg.rb
Library/Homebrew/cask/artifact/pkg.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "plist" require "utils/user" require "cask/artifact/abstract_artifact" require "extend/hash/keys" module Cask module Artifact # Artifact corresponding to the `pkg` stanza. class Pkg < AbstractArtifact attr_reader :path, :stanza_options def self.from_args(cask, path, **stanza_options) stanza_options.assert_valid_keys(:allow_untrusted, :choices) new(cask, path, **stanza_options) end def initialize(cask, path, **stanza_options) super @path = cask.staged_path.join(path) @stanza_options = stanza_options end def summarize path.relative_path_from(cask.staged_path).to_s end def install_phase(**options) run_installer(**options) end private def run_installer(command: nil, verbose: false, **_options) ohai "Running installer for #{cask} with `sudo` (which may request your password)..." unless path.exist? pkg = path.relative_path_from(cask.staged_path) pkgs = Pathname.glob(cask.staged_path/"**"/"*.pkg").map { |path| path.relative_path_from(cask.staged_path) } message = "Could not find PKG source file '#{pkg}'" message += ", found #{pkgs.map { |path| "'#{path}'" }.to_sentence} instead" if pkgs.any? message += "." raise CaskError, message end args = [ "-pkg", path, "-target", "/" ] args << "-verboseR" if verbose args << "-allowUntrusted" if stanza_options.fetch(:allow_untrusted, false) with_choices_file do |choices_path| args << "-applyChoiceChangesXML" << choices_path if choices_path env = { "LOGNAME" => User.current, "USER" => User.current, "USERNAME" => User.current, } command.run!( "/usr/sbin/installer", sudo: true, sudo_as_root: true, args:, print_stdout: true, env:, ) end end def with_choices_file choices = stanza_options.fetch(:choices, {}) return yield nil if choices.empty? Tempfile.open(["choices", ".xml"]) do |file| file.write Plist::Emit.dump(choices) file.close yield file.path ensure file.unlink 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/cask/artifact/vst3_plugin.rb
Library/Homebrew/cask/artifact/vst3_plugin.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `vst3_plugin` stanza. class Vst3Plugin < Moved sig { returns(String) } def self.english_name "VST3 Plugin" 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/artifact/relocated.rb
Library/Homebrew/cask/artifact/relocated.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "cask/artifact/abstract_artifact" require "extend/hash/keys" module Cask module Artifact # Superclass for all artifacts which have a source and a target location. class Relocated < AbstractArtifact def self.from_args(cask, *args) source_string, target_hash = args if target_hash raise CaskInvalidError, cask unless target_hash.respond_to?(:keys) target_hash.assert_valid_keys(:target) end target_hash ||= {} new(cask, source_string, **target_hash) end def resolve_target(target, base_dir: config.public_send(self.class.dirmethod)) target = Pathname(target) if target.relative? return target.expand_path if target.descend.first.to_s == "~" return base_dir/target if base_dir end target end sig { params(cask: Cask, source: T.nilable(T.any(String, Pathname)), target_hash: T.any(String, Pathname)) .void } def initialize(cask, source, **target_hash) super target = target_hash[:target] @source = nil @source_string = source.to_s @target = nil @target_string = target.to_s end def source @source ||= begin base_path = cask.staged_path base_path = base_path.join(cask.url.only_path) if cask.url&.only_path.present? base_path.join(@source_string) end end def target @target ||= resolve_target(@target_string.presence || source.basename) end def to_a [@source_string].tap do |ary| ary << { target: @target_string } unless @target_string.empty? end end sig { override.returns(String) } def summarize target_string = @target_string.empty? ? "" : " -> #{@target_string}" "#{@source_string}#{target_string}" end private ALT_NAME_ATTRIBUTE = "com.apple.metadata:kMDItemAlternateNames" private_constant :ALT_NAME_ATTRIBUTE # Try to make the asset searchable under the target name. Spotlight # respects this attribute for many filetypes, but ignores it for App # bundles. Alfred 2.2 respects it even for App bundles. sig { params(file: Pathname, altname: Pathname, command: T.class_of(SystemCommand)).returns(T.nilable(SystemCommand::Result)) } def add_altname_metadata(file, altname, command:) return if altname.to_s.casecmp(file.basename.to_s)&.zero? odebug "Adding #{ALT_NAME_ATTRIBUTE} metadata" altnames = command.run("/usr/bin/xattr", args: ["-p", ALT_NAME_ATTRIBUTE, file], print_stderr: false).stdout.sub(/\A\((.*)\)\Z/, '\1') odebug "Existing metadata is: #{altnames}" altnames.concat(", ") unless altnames.empty? altnames.concat(%Q("#{altname}")) altnames = "(#{altnames})" # Some packages are shipped as u=rx (e.g. Bitcoin Core) command.run!("chmod", args: ["--", "u+rw", file, file.realpath], sudo: !file.writable? || !file.realpath.writable?) command.run!("/usr/bin/xattr", args: ["-w", ALT_NAME_ATTRIBUTE, altnames, file], print_stderr: false, sudo: !file.writable?) end def printable_target target.to_s.sub(/^#{Dir.home}(#{File::SEPARATOR}|$)/, "~/") end end end end require "extend/os/cask/artifact/relocated"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/artifact/suite.rb
Library/Homebrew/cask/artifact/suite.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `suite` stanza. class Suite < Moved sig { returns(String) } def self.english_name "App Suite" end sig { returns(Symbol) } def self.dirmethod :appdir 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/artifact/colorpicker.rb
Library/Homebrew/cask/artifact/colorpicker.rb
# typed: strict # frozen_string_literal: true require "cask/artifact/moved" module Cask module Artifact # Artifact corresponding to the `colorpicker` stanza. class Colorpicker < Moved end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/aliases/aliases.rb
Library/Homebrew/aliases/aliases.rb
# typed: strict # frozen_string_literal: true require "aliases/alias" require "utils/output" module Homebrew module Aliases extend Utils::Output::Mixin RESERVED = T.let(( Commands.internal_commands + Commands.internal_developer_commands + Commands.internal_commands_aliases + %w[alias unalias] ).freeze, T::Array[String]) sig { void } def self.init FileUtils.mkdir_p HOMEBREW_ALIASES end sig { params(name: String, command: String).void } def self.add(name, command) new_alias = Alias.new(name, command) odie "alias 'brew #{name}' already exists!" if new_alias.script.exist? new_alias.write end sig { params(name: String).void } def self.remove(name) Alias.new(name).remove end sig { params(only: T::Array[String], block: T.proc.params(name: String, command: String).void).void } def self.each(only, &block) Dir["#{HOMEBREW_ALIASES}/*"].each do |path| next if path.end_with? "~" # skip Emacs-like backup files next if File.directory?(path) _shebang, meta, *lines = File.readlines(path) name = T.must(meta)[/alias: brew (\S+)/, 1] || File.basename(path) next if !only.empty? && only.exclude?(name) lines.reject! { |line| line.start_with?("#") || line =~ /^\s*$/ } first_line = lines.fetch(0) command = first_line.chomp command.sub!(/ \$\*$/, "") if command.start_with? "brew " command.sub!(/^brew /, "") else command = "!#{command}" end yield name, command if block.present? end end sig { params(aliases: String).void } def self.show(*aliases) each([*aliases]) do |name, command| puts "brew alias #{name}='#{command}'" existing_alias = Alias.new(name, command) existing_alias.link unless existing_alias.symlink.exist? end end sig { params(name: String, command: T.nilable(String)).void } def self.edit(name, command = nil) Alias.new(name, command).write unless command.nil? Alias.new(name, command).edit end sig { void } def self.edit_all exec_editor(*Dir[HOMEBREW_ALIASES]) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/aliases/alias.rb
Library/Homebrew/aliases/alias.rb
# typed: strict # frozen_string_literal: true require "fileutils" require "utils/output" module Homebrew module Aliases class Alias include ::Utils::Output::Mixin sig { returns(String) } attr_accessor :name sig { returns(T.nilable(String)) } attr_accessor :command sig { params(name: String, command: T.nilable(String)).void } def initialize(name, command = nil) @name = T.let(name.strip, String) @command = T.let(nil, T.nilable(String)) @script = T.let(nil, T.nilable(Pathname)) @symlink = T.let(nil, T.nilable(Pathname)) @command = if command&.start_with?("!", "%") command[1..] elsif command "brew #{command}" end end sig { returns(T::Boolean) } def reserved? RESERVED.include? name end sig { returns(T::Boolean) } def cmd_exists? path = which("brew-#{name}.rb") || which("brew-#{name}") !path.nil? && path.realpath.parent != HOMEBREW_ALIASES end sig { returns(Pathname) } def script @script ||= Pathname.new("#{HOMEBREW_ALIASES}/#{name.gsub(/\W/, "_")}") end sig { returns(Pathname) } def symlink @symlink ||= Pathname.new("#{HOMEBREW_PREFIX}/bin/brew-#{name}") end sig { returns(T::Boolean) } def valid_symlink? symlink.realpath.parent == HOMEBREW_ALIASES.realpath rescue NameError false end sig { void } def link FileUtils.rm symlink if File.symlink? symlink FileUtils.ln_s script, symlink end sig { params(opts: T::Hash[Symbol, T::Boolean]).void } def write(opts = {}) odie "'#{name}' is a reserved command. Sorry." if reserved? odie "'brew #{name}' already exists. Sorry." if cmd_exists? return if !opts[:override] && script.exist? content = if command <<~EOS #: * `#{name}` [args...] #: `brew #{name}` is an alias for `#{command}` #{command} $* EOS else <<~EOS #: * `#{name}` [args...] #: `brew #{name}` is an alias for *command* # This is a Homebrew alias script. It'll be called when the user # types `brew #{name}`. Any remaining arguments are passed to # this script. You can retrieve those with $*, or only the first # one with $1. Please keep your script on one line. # TODO: Replace the line below with your script echo "Hello I'm 'brew "#{name}"' and my args are:" $* EOS end script.open("w") do |f| f.write <<~EOS #! #{`which bash`.chomp} # alias: brew #{name} #{content} EOS end script.chmod 0744 link end sig { void } def remove odie "'brew #{name}' is not aliased to anything." if !symlink.exist? || !valid_symlink? script.unlink symlink.unlink end sig { void } def edit write(override: false) exec_editor script.to_s end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_installer_bottle_spec.rb
Library/Homebrew/test/formula_installer_bottle_spec.rb
# frozen_string_literal: true require "formula" require "formula_installer" require "keg" require "tab" require "cmd/install" require "test/support/fixtures/testball" require "test/support/fixtures/testball_bottle" require "test/support/fixtures/testball_bottle_cellar" RSpec.describe FormulaInstaller do alias_matcher :pour_bottle, :be_pour_bottle matcher :be_poured_from_bottle do match(&:poured_from_bottle) end def temporarily_install_bottle(formula) expect(formula).not_to be_latest_version_installed expect(formula).to be_bottled expect(formula).to pour_bottle stub_formula_loader formula("gcc") { url "gcc-1.0" } stub_formula_loader formula("glibc") { url "glibc-1.0" } stub_formula_loader formula fi = FormulaInstaller.new(formula) fi.fetch fi.install keg = Keg.new(formula.prefix) expect(formula).to be_latest_version_installed begin expect(keg.tab).to be_poured_from_bottle yield formula ensure keg.unlink keg.uninstall formula.clear_cache formula.bottle.clear_cache end expect(keg).not_to exist expect(formula).not_to be_latest_version_installed end def test_basic_formula_setup(formula) # Test that things made it into the Keg expect(formula.bin).to be_a_directory expect(formula.libexec).to be_a_directory expect(formula.prefix/"main.c").not_to exist # Test that things made it into the Cellar keg = Keg.new formula.prefix keg.link bin = HOMEBREW_PREFIX/"bin" expect(bin).to be_a_directory expect(formula.libexec).to be_a_directory end # This test wraps expect() calls in `test_basic_formula_setup` # rubocop:disable RSpec/NoExpectationExample specify "basic bottle install" do allow(DevelopmentTools).to receive(:installed?).and_return(false) Homebrew::Cmd::InstallCmd.new(["testball_bottle"]) temporarily_install_bottle(TestballBottle.new) do |f| test_basic_formula_setup(f) end end # rubocop:enable RSpec/NoExpectationExample specify "basic bottle install with cellar information on sha256 line" do allow(DevelopmentTools).to receive(:installed?).and_return(false) Homebrew::Cmd::InstallCmd.new(["testball_bottle_cellar"]) temporarily_install_bottle(TestballBottleCellar.new) do |f| test_basic_formula_setup(f) # skip_relocation is always false on Linux but can be true on macOS. # see: extend/os/linux/software_spec.rb skip_relocation = !OS.linux? expect(f.bottle_specification.skip_relocation?).to eq(skip_relocation) end end specify "build tools error" do allow(DevelopmentTools).to receive(:installed?).and_return(false) # Testball doesn't have a bottle block, so use it to test this behavior formula = Testball.new expect(formula).not_to be_latest_version_installed expect(formula).not_to be_bottled expect do described_class.new(formula).install end.to raise_error(UnbottledError) expect(formula).not_to be_latest_version_installed end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_spec_selection_spec.rb
Library/Homebrew/test/formula_spec_selection_spec.rb
# frozen_string_literal: true require "formula" RSpec.describe Formula do describe "::new" do it "selects stable by default" do f = formula do url "foo-1.0" head "foo" end expect(f).to be_stable end it "selects stable when exclusive" do f = formula { url "foo-1.0" } expect(f).to be_stable end it "selects HEAD when exclusive" do f = formula { head "foo" } expect(f).to be_head end it "does not select an incomplete spec" do f = formula do sha256 TEST_SHA256 version "1.0" head "foo" end expect(f).to be_head end it "does not set an incomplete stable spec" do f = formula do sha256 TEST_SHA256 head "foo" end expect(f.stable).to be_nil expect(f).to be_head end it "selects HEAD when requested" do f = formula("test", spec: :head) do url "foo-1.0" head "foo" end expect(f).to be_head end it "does not raise an error for a missing spec" do f = formula("test", spec: :head) do url "foo-1.0" end expect(f).to be_stable end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/pathname_spec.rb
Library/Homebrew/test/pathname_spec.rb
# frozen_string_literal: true require "extend/pathname" require "install_renamed" RSpec.describe Pathname do include FileUtils let(:src) { mktmpdir } let(:dst) { mktmpdir } let(:file) { src/"foo" } let(:dir) { src/"bar" } describe DiskUsageExtension do before do mkdir_p dir/"a-directory" touch [dir/".DS_Store", dir/"a-file"] File.truncate(dir/"a-file", 1_048_576) ln_s dir/"a-file", dir/"a-symlink" ln dir/"a-file", dir/"a-hardlink" end describe "#file_count" do it "returns the number of files in a directory" do expect(dir.file_count).to eq(3) end end describe "#abv" do context "when called on a directory" do it "returns a string with the file count and disk usage" do expect(dir.abv).to eq("3 files, 1MB") end end context "when called on a file" do it "returns the disk usage" do expect((dir/"a-file").abv).to eq("1MB") end end end end describe "#rmdir_if_possible" do before { mkdir_p dir } it "returns true and removes a directory if it doesn't contain files" do expect(dir.rmdir_if_possible).to be true expect(dir).not_to exist end it "returns false and doesn't delete a directory if it contains files" do touch dir/"foo" expect(dir.rmdir_if_possible).to be false expect(dir).to be_a_directory end it "ignores .DS_Store files" do touch dir/".DS_Store" expect(dir.rmdir_if_possible).to be true expect(dir).not_to exist end end describe "#append_lines" do it "appends lines to a file" do touch file file.append_lines("CONTENT") expect(File.read(file)).to eq <<~EOS CONTENT EOS file.append_lines("CONTENTS") expect(File.read(file)).to eq <<~EOS CONTENT CONTENTS EOS end it "raises an error if the file does not exist" do expect(file).not_to exist expect { file.append_lines("CONTENT") }.to raise_error(RuntimeError) end end describe "#atomic_write" do it "atomically replaces a file" do touch file file.atomic_write("CONTENT") expect(File.read(file)).to eq("CONTENT") end it "preserves permissions" do File.open(file, "w", 0100777) do # do nothing end file.atomic_write("CONTENT") expect(file.stat.mode.to_s(8)).to eq((~File.umask & 0100777).to_s(8)) end it "preserves default permissions" do file.atomic_write("CONTENT") sentinel = file.dirname.join("sentinel") touch sentinel expect(file.stat.mode.to_s(8)).to eq(sentinel.stat.mode.to_s(8)) end end describe "#ensure_writable" do it "makes a file writable and restores permissions afterwards" do skip "User is root so everything is writable." if Process.euid.zero? touch file chmod 0555, file expect(file).not_to be_writable file.ensure_writable do expect(file).to be_writable end expect(file).not_to be_writable end end describe "#extname" do it "supports common multi-level archives" do expect(described_class.new("foo-0.1.tar.gz").extname).to eq(".tar.gz") expect(described_class.new("foo-0.1.cpio.gz").extname).to eq(".cpio.gz") end it "does not treat version numbers as extensions" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new("foo-0.1").extname).to eq("") expect(described_class.new("foo-1.0-rc1").extname).to eq("") expect(described_class.new("foo-1.2.3").extname).to eq "" end it "supports `.7z` with version numbers" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new("snap7-full-1.4.2.7z").extname).to eq ".7z" end end describe "#stem" do it "returns the basename without double extensions" do expect(Pathname("foo-0.1.tar.gz").stem).to eq("foo-0.1") expect(Pathname("foo-0.1.cpio.gz").stem).to eq("foo-0.1") end end describe "#install" do before do (src/"a.txt").write "This is sample file a." (src/"b.txt").write "This is sample file b." end it "raises an error if the file doesn't exist" do expect { dst.install "non_existent_file" }.to raise_error(Errno::ENOENT) end it "installs a file to a directory with its basename" do touch file dst.install(file) expect(dst/file.basename).to exist expect(file).not_to exist end it "creates intermediate directories" do touch file expect(dir).not_to be_a_directory dir.install(file) expect(dir).to be_a_directory end it "can install a file" do dst.install src/"a.txt" expect(dst/"a.txt").to exist, "a.txt was not installed" expect(dst/"b.txt").not_to exist, "b.txt was installed." end it "can install an array of files" do dst.install [src/"a.txt", src/"b.txt"] expect(dst/"a.txt").to exist, "a.txt was not installed" expect(dst/"b.txt").to exist, "b.txt was not installed" end it "can install a directory" do bin = src/"bin" bin.mkpath mv Dir[src/"*.txt"], bin dst.install bin expect(dst/"bin/a.txt").to exist, "a.txt was not installed" expect(dst/"bin/b.txt").to exist, "b.txt was not installed" end it "supports renaming files" do dst.install src/"a.txt" => "c.txt" expect(dst/"c.txt").to exist, "c.txt was not installed" expect(dst/"a.txt").not_to exist, "a.txt was installed but not renamed" expect(dst/"b.txt").not_to exist, "b.txt was installed" end it "supports renaming multiple files" do dst.install(src/"a.txt" => "c.txt", src/"b.txt" => "d.txt") expect(dst/"c.txt").to exist, "c.txt was not installed" expect(dst/"d.txt").to exist, "d.txt was not installed" expect(dst/"a.txt").not_to exist, "a.txt was installed but not renamed" expect(dst/"b.txt").not_to exist, "b.txt was installed but not renamed" end it "supports renaming directories" do bin = src/"bin" bin.mkpath mv Dir[src/"*.txt"], bin dst.install bin => "libexec" expect(dst/"bin").not_to exist, "bin was installed but not renamed" expect(dst/"libexec/a.txt").to exist, "a.txt was not installed" expect(dst/"libexec/b.txt").to exist, "b.txt was not installed" end it "can install directories as relative symlinks" do bin = src/"bin" bin.mkpath mv Dir[src/"*.txt"], bin dst.install_symlink bin expect(dst/"bin").to be_a_symlink expect(dst/"bin").to be_a_directory expect(dst/"bin/a.txt").to exist expect(dst/"bin/b.txt").to exist expect((dst/"bin").readlink).to be_relative end it "can install relative paths as symlinks" do dst.install_symlink "foo" => "bar" expect((dst/"bar").readlink).to eq(described_class.new("foo")) end it "can install relative symlinks in a symlinked directory" do mkdir_p dst/"1/2" dst.install_symlink "1/2" => "12" expect((dst/"12").readlink).to eq(described_class.new("1/2")) (dst/"12").install_symlink dst/"foo" expect((dst/"12/foo").readlink).to eq(described_class.new("../../foo")) end end describe InstallRenamed do before do dst.extend(described_class) end it "renames the installed file if it already exists" do file.write "a" dst.install file file.write "b" dst.install file expect(File.read(dst/file.basename)).to eq("a") expect(File.read(dst/"#{file.basename}.default")).to eq("b") end it "renames the installed directory" do file.write "a" dst.install src expect(File.read(dst/src.basename/file.basename)).to eq("a") end it "recursively renames directories" do (dst/dir.basename).mkpath (dst/dir.basename/"another_file").write "a" dir.mkpath (dir/"another_file").write "b" dst.install dir expect(File.read(dst/dir.basename/"another_file.default")).to eq("b") end end describe "#cp_path_sub" do it "copies a file and replaces the given pattern" do file.write "a" file.cp_path_sub src, dst expect(File.read(dst/file.basename)).to eq("a") end it "copies a directory and replaces the given pattern" do dir.mkpath dir.cp_path_sub src, dst expect(dst/dir.basename).to be_a_directory end end describe "#ds_store?" do it "returns whether a file is .DS_Store or not" do expect(file).not_to be_ds_store expect(file/".DS_Store").to be_ds_store end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/macos_runner_spec_spec.rb
Library/Homebrew/test/macos_runner_spec_spec.rb
# frozen_string_literal: true require "macos_runner_spec" RSpec.describe MacOSRunnerSpec do let(:spec) { described_class.new(name: "macOS 11-arm64", runner: "11-arm64", timeout: 90, cleanup: true) } it "has immutable attributes" do [:name, :runner, :timeout, :cleanup].each do |attribute| expect(spec.respond_to?(:"#{attribute}=")).to be(false) end end describe "#to_h" do it "returns an object that responds to `#to_json`" do expect(spec.to_h.respond_to?(:to_json)).to be(true) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/linkage_cache_store_spec.rb
Library/Homebrew/test/linkage_cache_store_spec.rb
# frozen_string_literal: true require "linkage_cache_store" RSpec.describe LinkageCacheStore do subject(:linkage_cache) { described_class.new(keg_name, database) } let(:keg_name) { "keg_name" } let(:database) { instance_double(CacheStoreDatabase, "database") } describe "#keg_exists?" do context "when `keg_name` exists in cache" do it "returns `true`" do expect(database).to receive(:get).with(keg_name).and_return("") expect(linkage_cache.keg_exists?).to be(true) end end context "when `keg_name` does not exist in cache" do it "returns `false`" do expect(database).to receive(:get).with(keg_name).and_return(nil) expect(linkage_cache.keg_exists?).to be(false) end end end describe "#update!" do context "when a `value` is a `Hash`" do it "sets the cache for the `keg_name`" do expect(database).to receive(:set).with(keg_name, anything) linkage_cache.update!(keg_files_dylibs: { key: ["value"] }) end end context "when a `value` is not a `Hash`" do it "raises a `TypeError` if a `value` is not a `Hash`" do expect { linkage_cache.update!(a_value: ["value"]) }.to raise_error(TypeError) end end end describe "#delete!" do it "calls `delete` on the `database` with `keg_name` as parameter" do expect(database).to receive(:delete).with(keg_name) linkage_cache.delete! end end describe "#fetch" do context "when `HASH_LINKAGE_TYPES.include?(type)`" do it "returns a `Hash` of values" do expect(database).to receive(:get).with(keg_name).and_return(nil) expect(linkage_cache.fetch(:keg_files_dylibs)).to be_an_instance_of(Hash) end end context "when `type` is not in `HASH_LINKAGE_TYPES`" do it "raises a `TypeError` if the `type` is not supported" do expect { linkage_cache.fetch(:bad_type) }.to raise_error(TypeError) end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/sbom_spec.rb
Library/Homebrew/test/sbom_spec.rb
# frozen_string_literal: true require "sbom" RSpec.describe SBOM do describe "#schema_validation_errors" do subject(:sbom) { described_class.create(f, tab) } before { ENV.delete("HOMEBREW_ENFORCE_SBOM") } let(:f) { formula { url "foo-1.0" } } let(:tab) { Tab.new } it "returns true if valid" do expect(sbom.schema_validation_errors).to be_empty end it "returns true if valid when bottling" do expect(sbom.schema_validation_errors(bottling: true)).to be_empty end context "with a maximal SBOM" do let(:f) do formula do homepage "https://brew.sh" url "https://brew.sh/test-0.1.tbz" sha256 TEST_SHA256 patch do url "patch_macos" end bottle do sha256 all: "9befdad158e59763fb0622083974a6252878019702d8c961e1bec3a5f5305339" end # some random dependencies to test with depends_on "cmake" => :build depends_on "beanstalkd" uses_from_macos "python" => :build uses_from_macos "zlib" end end let(:tab) do beanstalkd = formula "beanstalkd" do url "one-1.1" bottle do sha256 all: "ac4c0330b70dae06eaa8065bfbea78dda277699d1ae8002478017a1bd9cf1908" end end zlib = formula "zlib" do url "two-1.1" bottle do sha256 all: "6a4642964fe5c4d1cc8cd3507541736d5b984e34a303a814ef550d4f2f8242f9" end end runtime_dependencies = [beanstalkd, zlib] runtime_deps_hash = runtime_dependencies.map do |dep| { "full_name" => dep.full_name, "version" => dep.version.to_s, "revision" => dep.revision, "pkg_version" => dep.pkg_version.to_s, "declared_directly" => true, } end allow(Tab).to receive(:runtime_deps_hash).and_return(runtime_deps_hash) tab = Tab.create(f, DevelopmentTools.default_compiler, :libcxx) allow(Formulary).to receive(:factory).with("beanstalkd").and_return(beanstalkd) allow(Formulary).to receive(:factory).with("zlib").and_return(zlib) tab end it "returns true if valid" do expect(sbom.schema_validation_errors).to be_empty end it "returns true if valid when bottling" do expect(sbom.schema_validation_errors(bottling: true)).to be_empty end end context "with an invalid SBOM" do before do allow(sbom).to receive(:to_spdx_sbom).and_return({}) # fake an empty SBOM end it "returns false" do expect(sbom.schema_validation_errors).not_to be_empty end it "returns false when bottling" do expect(sbom.schema_validation_errors(bottling: true)).not_to be_empty end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/macos_version_spec.rb
Library/Homebrew/test/macos_version_spec.rb
# frozen_string_literal: true require "macos_version" RSpec.describe MacOSVersion do let(:version) { described_class.new("10.15") } let(:tahoe_major) { described_class.new("26.0") } let(:big_sur_major) { described_class.new("11.0") } let(:big_sur_update) { described_class.new("11.1") } let(:frozen_version) { described_class.new("10.15").freeze } describe "::kernel_major_version" do it "returns the kernel major version" do expect(described_class.kernel_major_version(version)).to eq "19" expect(described_class.kernel_major_version(tahoe_major)).to eq "25" expect(described_class.kernel_major_version(big_sur_major)).to eq "20" expect(described_class.kernel_major_version(big_sur_update)).to eq "20" end it "matches the major version returned by OS.kernel_version", :needs_macos do expect(described_class.kernel_major_version(OS::Mac.version)).to eq OS.kernel_version.major end end describe "::from_symbol" do it "raises an error if the symbol is not a valid macOS version" do expect do described_class.from_symbol(:foo) end.to raise_error(MacOSVersion::Error, "unknown or unsupported macOS version: :foo") end it "creates a new version from a valid macOS version" do symbol_version = described_class.from_symbol(:catalina) expect(symbol_version).to eq(version) end end describe "#new" do it "raises an error if the version is not a valid macOS version" do expect do described_class.new("1.2") end.to raise_error(MacOSVersion::Error, 'unknown or unsupported macOS version: "1.2"') end it "creates a new version from a valid macOS version" do string_version = described_class.new("11") expect(string_version).to eq(:big_sur) end end specify "comparison with Symbol" do expect(version).to be >= :catalina expect(version).to eq :catalina # We're explicitly testing the `===` operator results here. expect(version).to be === :catalina # rubocop:disable Style/CaseEquality expect(version).to be < :tahoe # This should work like a normal comparison but the result won't be added # to the `@comparison_cache` hash because the object is frozen. expect(frozen_version).to eq :catalina expect(frozen_version.instance_variable_get(:@comparison_cache)).to eq({}) end specify "comparison with Integer" do expect(version).to be > 10 expect(version).to be < 11 end specify "comparison with String" do # rubocop:todo RSpec/AggregateExamples expect(version).to be > "10.3" expect(version).to eq "10.15" # We're explicitly testing the `===` operator results here. expect(version).to be === "10.15" # rubocop:disable Style/CaseEquality expect(version).to be < "11" end specify "comparison with Version" do # rubocop:todo RSpec/AggregateExamples expect(version).to be > Version.new("10.3") expect(version).to eq Version.new("10.15") # We're explicitly testing the `===` operator results here. expect(version).to be === Version.new("10.15") # rubocop:disable Style/CaseEquality expect(version).to be < Version.new("11") end describe "after Big Sur" do specify "comparison with :big_sur" do expect(big_sur_major).to eq :big_sur expect(big_sur_major).to be <= :big_sur expect(big_sur_major).to be >= :big_sur expect(big_sur_major).not_to be > :big_sur expect(big_sur_major).not_to be < :big_sur expect(big_sur_update).to eq :big_sur expect(big_sur_update).to be <= :big_sur expect(big_sur_update).to be >= :big_sur expect(big_sur_update).not_to be > :big_sur expect(big_sur_update).not_to be < :big_sur end end describe "#strip_patch" do let(:catalina_update) { described_class.new("10.15.1") } it "returns the version without the patch" do expect(big_sur_update.strip_patch).to eq(described_class.new("11")) expect(catalina_update.strip_patch).to eq(described_class.new("10.15")) end it "returns self if version is null" do # rubocop:todo RSpec/AggregateExamples expect(described_class::NULL.strip_patch).to be described_class::NULL end end specify "#to_sym" do version_symbol = :catalina # We call this more than once to exercise the caching logic expect(version.to_sym).to eq(version_symbol) expect(version.to_sym).to eq(version_symbol) # This should work like a normal but the symbol won't be stored as the # `@sym` instance variable because the object is frozen. expect(frozen_version.to_sym).to eq(version_symbol) expect(frozen_version.instance_variable_get(:@sym)).to be_nil expect(described_class::NULL.to_sym).to eq(:dunno) end specify "#pretty_name" do version_pretty_name = "Catalina" expect(described_class.new("11").pretty_name).to eq("Big Sur") # We call this more than once to exercise the caching logic expect(version.pretty_name).to eq(version_pretty_name) expect(version.pretty_name).to eq(version_pretty_name) # This should work like a normal but the computed name won't be stored as # the `@pretty_name` instance variable because the object is frozen. expect(frozen_version.pretty_name).to eq(version_pretty_name) expect(frozen_version.instance_variable_get(:@pretty_name)).to be_nil end specify "#inspect" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new("11").inspect).to eq("#<MacOSVersion: \"11\">") end specify "#outdated_release?" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new(described_class::SYMBOLS.values.first).outdated_release?).to be false expect(described_class.new("10.0").outdated_release?).to be true end specify "#prerelease?" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new("1000").prerelease?).to be true end specify "#unsupported_release?" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new("10.0").unsupported_release?).to be true expect(described_class.new("1000").prerelease?).to be true end describe "#requires_nehalem_cpu?", :needs_macos do context "when CPU is Intel" do it "returns true if version requires a Nehalem CPU" do allow(Hardware::CPU).to receive(:type).and_return(:intel) expect(described_class.new("10.15").requires_nehalem_cpu?).to be true end end context "when CPU is not Intel" do it "raises an error" do allow(Hardware::CPU).to receive(:type).and_return(:arm) expect { described_class.new("10.15").requires_nehalem_cpu? } .to raise_error(ArgumentError) end end it "returns false when version is null" do expect(described_class::NULL.requires_nehalem_cpu?).to be false end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/requirement_spec.rb
Library/Homebrew/test/requirement_spec.rb
# frozen_string_literal: true require "extend/ENV" require "requirement" RSpec.describe Requirement do alias_matcher :be_a_build_requirement, :be_a_build subject(:requirement) { klass.new } let(:klass) { Class.new(described_class) } describe "base class" do it "raises an error when instantiated" do expect { described_class.new } .to raise_error(RuntimeError, "Requirement is declared as abstract; it cannot be instantiated") end end describe "#tags" do subject(:req) { klass.new(tags) } context "with a single tag" do let(:tags) { ["bar"] } it(:tags) { expect(req.tags).to eq(tags) } end context "with multiple tags" do let(:tags) { ["bar", "baz"] } it(:tags) { expect(req.tags).to eq(tags) } end context "with symbol tags" do let(:tags) { [:build] } it(:tags) { expect(req.tags).to eq(tags) } end context "with symbol and string tags" do let(:tags) { [:build, "bar"] } it(:tags) { expect(req.tags).to eq(tags) } end end describe "#fatal?" do describe "#fatal true is specified" do let(:klass) do Class.new(described_class) do fatal true end end it { is_expected.to be_fatal } end describe "#fatal is omitted" do it { is_expected.not_to be_fatal } end end describe "#satisfied?" do describe "#satisfy with block and build_env returns true" do let(:klass) do Class.new(described_class) do satisfy(build_env: false) do true end end end it { is_expected.to be_satisfied } end describe "#satisfy with block and build_env returns false" do let(:klass) do Class.new(described_class) do satisfy(build_env: false) do false end end end it { is_expected.not_to be_satisfied } end describe "#satisfy returns true" do let(:klass) do Class.new(described_class) do satisfy true end end it { is_expected.to be_satisfied } end describe "#satisfy returns false" do let(:klass) do Class.new(described_class) do satisfy false end end it { is_expected.not_to be_satisfied } end describe "#satisfy with block returning true and without :build_env" do let(:klass) do Class.new(described_class) do satisfy do true end end end it "sets up build environment" do expect(ENV).to receive(:with_build_environment).and_call_original requirement.satisfied? end end describe "#satisfy with block returning true and :build_env set to false" do let(:klass) do Class.new(described_class) do satisfy(build_env: false) do true end end end it "skips setting up build environment" do expect(ENV).not_to receive(:with_build_environment) requirement.satisfied? end end describe "#satisfy with block returning path and without :build_env" do let(:klass) do Class.new(described_class) do satisfy do Pathname.new("/foo/bar/baz") end end end it "infers path from #satisfy result" do without_partial_double_verification do expect(ENV).to receive(:prepend_path).with("PATH", Pathname.new("/foo/bar")) end requirement.satisfied? requirement.modify_build_environment end end end describe "#build?" do context "when the :build tag is specified" do subject { klass.new([:build]) } it { is_expected.to be_a_build_requirement } end describe "#build omitted" do it { is_expected.not_to be_a_build_requirement } end end describe "#name and #option_names" do let(:const) { :FooRequirement } let(:klass) { self.class.const_get(const) } before do stub_const const.to_s, Class.new(described_class) end it(:name) { expect(requirement.name).to eq("foo") } it(:option_names) { expect(requirement.option_names).to eq(["foo"]) } end describe "#modify_build_environment" do context "without env proc" do let(:klass) { Class.new(described_class) } it "returns nil" do expect { requirement.modify_build_environment }.not_to raise_error end end end describe "#eql? and #==" do subject(:requirement) { klass.new } it "returns true if the names and tags are equal" do other = klass.new expect(requirement).to eql(other) expect(requirement).to eq(other) end it "returns false if names differ" do other = klass.new allow(other).to receive(:name).and_return("foo") expect(requirement).not_to eql(other) expect(requirement).not_to eq(other) end it "returns false if tags differ" do other = klass.new([:optional]) expect(requirement).not_to eql(other) expect(requirement).not_to eq(other) end end describe "#hash" do subject(:requirement) { klass.new } it "is equal if names and tags are equal" do other = klass.new expect(requirement.hash).to eq(other.hash) end it "differs if names differ" do other = klass.new allow(other).to receive(:name).and_return("foo") expect(requirement.hash).not_to eq(other.hash) end it "differs if tags differ" do other = klass.new([:optional]) expect(requirement.hash).not_to eq(other.hash) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/search_spec.rb
Library/Homebrew/test/search_spec.rb
# frozen_string_literal: true require "search" require "descriptions" require "cmd/desc" RSpec.describe Homebrew::Search do describe "#query_regexp" do it "correctly parses a regex query" do expect(described_class.query_regexp("/^query$/")).to eq(/^query$/) end it "returns the original string if it is not a regex query" do expect(described_class.query_regexp("query")).to eq("query") end it "raises an error if the query is an invalid regex" do expect { described_class.query_regexp("/+/") }.to raise_error(/not a valid regex/) end end describe "#search" do let(:collection) { ["with-dashes", "with@alpha", "with+plus"] } context "when given a block" do let(:collection) { [["with-dashes", "withdashes"]] } it "searches by the selected argument" do expect(described_class.search(collection, /withdashes/) { |_, short_name| short_name }).not_to be_empty expect(described_class.search(collection, /withdashes/) { |long_name, _| long_name }).to be_empty end end context "when given a regex" do it "does not simplify strings" do expect(described_class.search(collection, /with-dashes/)).to eq ["with-dashes"] end end context "when given a string" do it "simplifies both the query and searched strings" do expect(described_class.search(collection, "with dashes")).to eq ["with-dashes"] end it "does not simplify strings with @ and + characters" do expect(described_class.search(collection, "with@alpha")).to eq ["with@alpha"] expect(described_class.search(collection, "with+plus")).to eq ["with+plus"] end end context "when searching a Hash" do let(:collection) { { "foo" => "bar" } } it "returns a Hash" do expect(described_class.search(collection, "foo")).to eq "foo" => "bar" end context "with a nil value" do let(:collection) { { "foo" => nil } } it "does not raise an error" do expect(described_class.search(collection, "foo")).to eq "foo" => nil end end end end describe "#search_descriptions" do let(:args) { Homebrew::Cmd::Desc.new(["min_arg_placeholder"]).args } context "with api" do let(:api_formulae) do { "testball" => { "desc" => "Some test" } } end let(:api_casks) do { "testball" => { "desc" => "Some test", "name" => ["Test Ball"] } } end before do allow(Homebrew::API::Formula).to receive(:all_formulae).and_return(api_formulae) allow(Homebrew::API::Cask).to receive(:all_casks).and_return(api_casks) end it "searches formula descriptions" do expect { described_class.search_descriptions(described_class.query_regexp("some"), args) } .to output(/testball: Some test/).to_stdout end it "searches cask descriptions", :needs_macos do expect { described_class.search_descriptions(described_class.query_regexp("ball"), args) } .to output(/testball: \(Test Ball\) Some test/).to_stdout .and not_to_output(/testball: Some test/).to_stdout end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/bottle_filename_spec.rb
Library/Homebrew/test/bottle_filename_spec.rb
# frozen_string_literal: true require "formula" require "software_spec" RSpec.describe Bottle::Filename do subject(:filename) { described_class.new(name, version, tag, rebuild) } let(:name) { "user/repo/foo" } let(:version) { PkgVersion.new(Version.new("1.0"), 0) } let(:tag) { Utils::Bottles::Tag.from_symbol(:x86_64_linux) } let(:rebuild) { 0 } describe "#extname" do it(:extname) { expect(filename.extname).to eq ".x86_64_linux.bottle.tar.gz" } context "when rebuild is 0" do it(:extname) { expect(filename.extname).to eq ".x86_64_linux.bottle.tar.gz" } end context "when rebuild is 1" do let(:rebuild) { 1 } it(:extname) { expect(filename.extname).to eq ".x86_64_linux.bottle.1.tar.gz" } end end describe "#to_s and #to_str" do it(:to_s) { expect(filename.to_s).to eq "foo--1.0.x86_64_linux.bottle.tar.gz" } it(:to_str) { expect(filename.to_str).to eq "foo--1.0.x86_64_linux.bottle.tar.gz" } end describe "#url_encode" do it(:url_encode) { expect(filename.url_encode).to eq "foo-1.0.x86_64_linux.bottle.tar.gz" } end describe "#github_packages" do it(:github_packages) { expect(filename.github_packages).to eq "foo--1.0.x86_64_linux.bottle.tar.gz" } end describe "#json" do it(:json) { expect(filename.json).to eq "foo--1.0.x86_64_linux.bottle.json" } context "when rebuild is 1" do it(:json) { expect(filename.json).to eq "foo--1.0.x86_64_linux.bottle.json" } end end describe "::create" do subject(:filename) { described_class.create(f, tag, rebuild) } let(:f) do formula do url "https://brew.sh/foo.tar.gz" version "1.0" end end it(:to_s) { expect(filename.to_s).to eq "formula_name--1.0.x86_64_linux.bottle.tar.gz" } end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/patching_spec.rb
Library/Homebrew/test/patching_spec.rb
# frozen_string_literal: true require "formula" RSpec.describe "patching", type: :system do let(:formula_subclass) do Class.new(Formula) do # These are defined within an anonymous class to avoid polluting the global namespace. # rubocop:disable RSpec/LeakyConstantDeclaration,Lint/ConstantDefinitionInBlock TESTBALL_URL = "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz".freeze TESTBALL_PATCHES_URL = "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1-patches.tgz".freeze PATCH_URL_A = "file://#{TEST_FIXTURE_DIR}/patches/noop-a.diff".freeze PATCH_URL_B = "file://#{TEST_FIXTURE_DIR}/patches/noop-b.diff".freeze PATCH_URL_D = "file://#{TEST_FIXTURE_DIR}/patches/noop-d.diff".freeze PATCH_A_CONTENTS = File.read("#{TEST_FIXTURE_DIR}/patches/noop-a.diff").freeze PATCH_B_CONTENTS = File.read("#{TEST_FIXTURE_DIR}/patches/noop-b.diff").freeze APPLY_A = "noop-a.diff" APPLY_B = "noop-b.diff" APPLY_C = "noop-c.diff" APPLY_D = "noop-d.diff" # rubocop:enable RSpec/LeakyConstantDeclaration,Lint/ConstantDefinitionInBlock url TESTBALL_URL sha256 TESTBALL_SHA256 end end def formula(name = "formula_name", path: Formulary.core_path(name), spec: :stable, alias_path: nil, &block) formula_subclass.class_eval(&block) formula_subclass.new(name, path, spec, alias_path:) end matcher :be_patched do match do |formula| formula.brew do formula.patch s = File.read("libexec/NOOP") expect(s).not_to include("NOOP"), "libexec/NOOP was not patched as expected" expect(s).to include("ABCD"), "libexec/NOOP was not patched as expected" end end end matcher :be_patched_with_homebrew_prefix do match do |formula| formula.brew do formula.patch s = File.read("libexec/NOOP") expect(s).not_to include("NOOP"), "libexec/NOOP was not patched as expected" expect(s).not_to include("@@HOMEBREW_PREFIX@@"), "libexec/NOOP was not patched as expected" expect(s).to include(HOMEBREW_PREFIX.to_s), "libexec/NOOP was not patched as expected" end end end matcher :have_its_resource_patched do match do |formula| formula.brew do formula.resources.first.stage Pathname.pwd/"resource_dir" s = File.read("resource_dir/libexec/NOOP") expect(s).not_to include("NOOP"), "libexec/NOOP was not patched as expected" expect(s).to include("ABCD"), "libexec/NOOP was not patched as expected" end end end matcher :be_sequentially_patched do match do |formula| formula.brew do formula.patch s = File.read("libexec/NOOP") expect(s).not_to include("NOOP"), "libexec/NOOP was not patched as expected" expect(s).not_to include("ABCD"), "libexec/NOOP was not patched as expected" expect(s).to include("1234"), "libexec/NOOP was not patched as expected" end end end matcher :miss_apply do match do |formula| expect do formula.brew do formula.patch end end.to raise_error(MissingApplyError) end end specify "single_patch_dsl" do expect( formula do patch do url PATCH_URL_A sha256 PATCH_A_SHA256 end end, ).to be_patched end specify "single_patch_dsl_for_resource" do expect( formula do resource "some_resource" do url TESTBALL_URL sha256 TESTBALL_SHA256 patch do url PATCH_URL_A sha256 PATCH_A_SHA256 end end end, ).to have_its_resource_patched end specify "single_patch_dsl_with_apply" do expect( formula do patch do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 apply APPLY_A end end, ).to be_patched end specify "single_patch_dsl_with_sequential_apply" do expect( formula do patch do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 apply APPLY_A, APPLY_C end end, ).to be_sequentially_patched end specify "single_patch_dsl_with_strip" do expect( formula do patch :p1 do url PATCH_URL_A sha256 PATCH_A_SHA256 end end, ).to be_patched end specify "single_patch_dsl_with_strip_with_apply" do expect( formula do patch :p1 do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 apply APPLY_A end end, ).to be_patched end specify "single_patch_dsl_with_incorrect_strip" do expect do f = formula do patch :p0 do url PATCH_URL_A sha256 PATCH_A_SHA256 end end f.brew { |formula, _staging| formula.patch } end.to raise_error(BuildError) end specify "single_patch_dsl_with_incorrect_strip_with_apply" do expect do f = formula do patch :p0 do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 apply APPLY_A end end f.brew { |formula, _staging| formula.patch } end.to raise_error(BuildError) end specify "patch_p0_dsl" do expect( formula do patch :p0 do url PATCH_URL_B sha256 PATCH_B_SHA256 end end, ).to be_patched end specify "patch_p0_dsl_with_apply" do expect( formula do patch :p0 do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 apply APPLY_B end end, ).to be_patched end specify "patch_string" do expect(formula { patch PATCH_A_CONTENTS }).to be_patched end specify "patch_string_with_strip" do expect(formula { patch :p0, PATCH_B_CONTENTS }).to be_patched end specify "single_patch_dsl_missing_apply_fail" do expect( formula do patch do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 end end, ).to miss_apply end specify "single_patch_dsl_with_apply_enoent_fail" do expect do f = formula do patch do url TESTBALL_PATCHES_URL sha256 TESTBALL_PATCHES_SHA256 apply "patches/#{APPLY_A}" end end f.brew { |formula, _staging| formula.patch } end.to raise_error(Errno::ENOENT) end specify "patch_dsl_with_homebrew_prefix" do expect( formula do patch do url PATCH_URL_D sha256 PATCH_D_SHA256 end end, ).to be_patched_with_homebrew_prefix end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/linux_runner_spec_spec.rb
Library/Homebrew/test/linux_runner_spec_spec.rb
# frozen_string_literal: true require "linux_runner_spec" RSpec.describe LinuxRunnerSpec do let(:spec) do described_class.new( name: "Linux", runner: "ubuntu-latest", container: { image: "ghcr.io/homebrew/ubuntu22.04:main", options: "--user=linuxbrew" }, workdir: "/github/home", timeout: 360, cleanup: false, ) end it "has immutable attributes" do [:name, :runner, :container, :workdir, :timeout, :cleanup].each do |attribute| expect(spec.respond_to?(:"#{attribute}=")).to be(false) end end describe "#to_h" do it "returns an object that responds to `#to_json`" do expect(spec.to_h.respond_to?(:to_json)).to be(true) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/version_spec.rb
Library/Homebrew/test/version_spec.rb
# frozen_string_literal: true require "version" RSpec.describe Version do subject(:version) { described_class.new("1.2.3") } specify ".formula_optionally_versioned_regex" do expect(described_class.formula_optionally_versioned_regex("foo")).to match("foo@1.2") end describe Version::Token do specify "#inspect" do expect(described_class.create("foo").inspect).to eq('#<Version::StringToken "foo">') end specify "#to_s" do # rubocop:todo RSpec/AggregateExamples expect(described_class.create("foo").to_s).to eq("foo") end it "can be compared against nil" do expect(described_class.create("2")).to be > nil expect(described_class.create("p194")).to be > nil end it "can be compared against `Version::NULL_TOKEN`" do expect(described_class.create("2")).to be > Version::NULL_TOKEN expect(described_class.create("p194")).to be > Version::NULL_TOKEN end it "can be compared against strings" do expect(described_class.create("2")).to eq "2" expect(described_class.create("p194")).to eq "p194" expect(described_class.create("1")).to eq 1 end specify "comparison returns nil for non-token" do v = described_class.create("1") expect(v <=> Object.new).to be_nil expect { v > Object.new }.to raise_error(ArgumentError) end describe "#to_str" do it "implicitly converts token to string" do expect(String.try_convert(described_class.create("foo"))).not_to be_nil end end end describe "#to_s" do it "returns a string" do expect(version.to_s).to eq "1.2.3" end end describe "#to_str" do it "returns a string" do expect(version.to_str).to eq "1.2.3" end end it "implicitlys converts to a string" do expect(String.try_convert(version)).to eq "1.2.3" end describe "#to_f" do it "returns a float" do expect(version.to_f).to eq 1.2 end end describe "#to_json" do it "returns a JSON string" do expect(version.to_json).to eq "\"1.2.3\"" end end describe "when the version is `NULL`" do subject(:null_version) { Version::NULL } it "is always smaller" do expect(null_version).to be < described_class.new("1") end it "is never greater" do # rubocop:todo RSpec/AggregateExamples expect(null_version).not_to be > described_class.new("0") end it "isn't equal to itself" do # rubocop:todo RSpec/AggregateExamples expect(null_version).not_to eql(null_version) end describe "#to_s" do it "returns an empty string" do expect(null_version.to_s).to eq "" end end describe "#to_str" do it "does not respond to it" do expect(null_version).not_to respond_to(:to_str) end it "raises an error" do expect do null_version.to_str end.to raise_error NoMethodError, "undefined method `to_str` for Version:NULL" end end it "does not implicitly convert to a string" do expect(String.try_convert(null_version)).to be_nil end describe "#to_f" do it "returns NaN" do expect(null_version.to_f).to be_nan end end describe "#to_json" do it "outputs `null`" do expect(null_version.to_json).to eq "null" end end end describe "::NULL_TOKEN" do subject(:null_version) { described_class::NULL_TOKEN } specify "#inspect" do expect(null_version.inspect).to eq("#<Version::NullToken>") end it "is equal to itself" do # rubocop:todo RSpec/AggregateExamples expect(null_version).to eq described_class::NULL_TOKEN end end specify "comparison" do expect(described_class.new("0.1")).to eq described_class.new("0.1.0") expect(described_class.new("0.1")).to be < described_class.new("0.2") expect(described_class.new("1.2.3")).to be > described_class.new("1.2.2") expect(described_class.new("1.2.4")).to be < described_class.new("1.2.4.1") expect(described_class.new("1.2.3")).to be > described_class.new("1.2.3alpha4") expect(described_class.new("1.2.3")).to be > described_class.new("1.2.3beta2") expect(described_class.new("1.2.3")).to be > described_class.new("1.2.3rc3") expect(described_class.new("1.2.3")).to be < described_class.new("1.2.3-p34") end specify "compare" do expect(described_class.new("0.1").compare("==", described_class.new("0.1.0"))).to be true expect(described_class.new("0.1").compare("<", described_class.new("0.2"))).to be true expect(described_class.new("1.2.3").compare(">", described_class.new("1.2.2"))).to be true expect(described_class.new("1.2.4").compare("<", described_class.new("1.2.4.1"))).to be true expect(described_class.new("0.1").compare("!=", described_class.new("0.1.0"))).to be false expect(described_class.new("0.1").compare(">=", described_class.new("0.2"))).to be false expect(described_class.new("1.2.3").compare("<=", described_class.new("1.2.2"))).to be false expect(described_class.new("1.2.4").compare(">=", described_class.new("1.2.4.1"))).to be false expect(described_class.new("1.2.3").compare(">", described_class.new("1.2.3alpha4"))).to be true expect(described_class.new("1.2.3").compare(">", described_class.new("1.2.3beta2"))).to be true expect(described_class.new("1.2.3").compare(">", described_class.new("1.2.3rc3"))).to be true expect(described_class.new("1.2.3").compare("<", described_class.new("1.2.3-p34"))).to be true expect(described_class.new("1.2.3").compare("<=", described_class.new("1.2.3alpha4"))).to be false expect(described_class.new("1.2.3").compare("<=", described_class.new("1.2.3beta2"))).to be false expect(described_class.new("1.2.3").compare("<=", described_class.new("1.2.3rc3"))).to be false expect(described_class.new("1.2.3").compare(">=", described_class.new("1.2.3-p34"))).to be false end specify "HEAD" do expect(described_class.new("HEAD")).to be > described_class.new("1.2.3") expect(described_class.new("HEAD-abcdef")).to be > described_class.new("1.2.3") expect(described_class.new("1.2.3")).to be < described_class.new("HEAD") expect(described_class.new("1.2.3")).to be < described_class.new("HEAD-fedcba") expect(described_class.new("HEAD-abcdef")).to eq described_class.new("HEAD-fedcba") expect(described_class.new("HEAD")).to eq described_class.new("HEAD-fedcba") end specify "comparing alpha versions" do expect(described_class.new("1.2.3alpha")).to be < described_class.new("1.2.3") expect(described_class.new("1.2.3")).to be < described_class.new("1.2.3a") expect(described_class.new("1.2.3alpha4")).to eq described_class.new("1.2.3a4") expect(described_class.new("1.2.3alpha4")).to eq described_class.new("1.2.3A4") expect(described_class.new("1.2.3alpha4")).to be > described_class.new("1.2.3alpha3") expect(described_class.new("1.2.3alpha4")).to be < described_class.new("1.2.3alpha5") expect(described_class.new("1.2.3alpha4")).to be < described_class.new("1.2.3alpha10") expect(described_class.new("1.2.3alpha4")).to be < described_class.new("1.2.3beta2") expect(described_class.new("1.2.3alpha4")).to be < described_class.new("1.2.3rc3") expect(described_class.new("1.2.3alpha4")).to be < described_class.new("1.2.3") expect(described_class.new("1.2.3alpha4")).to be < described_class.new("1.2.3-p34") end specify "comparing beta versions" do expect(described_class.new("1.2.3beta2")).to eq described_class.new("1.2.3b2") expect(described_class.new("1.2.3beta2")).to eq described_class.new("1.2.3B2") expect(described_class.new("1.2.3beta2")).to be > described_class.new("1.2.3beta1") expect(described_class.new("1.2.3beta2")).to be < described_class.new("1.2.3beta3") expect(described_class.new("1.2.3beta2")).to be < described_class.new("1.2.3beta10") expect(described_class.new("1.2.3beta2")).to be > described_class.new("1.2.3alpha4") expect(described_class.new("1.2.3beta2")).to be < described_class.new("1.2.3rc3") expect(described_class.new("1.2.3beta2")).to be < described_class.new("1.2.3") expect(described_class.new("1.2.3beta2")).to be < described_class.new("1.2.3-p34") end specify "comparing pre versions" do expect(described_class.new("1.2.3pre9")).to eq described_class.new("1.2.3PRE9") expect(described_class.new("1.2.3pre9")).to be > described_class.new("1.2.3pre8") expect(described_class.new("1.2.3pre8")).to be < described_class.new("1.2.3pre9") expect(described_class.new("1.2.3pre9")).to be < described_class.new("1.2.3pre10") expect(described_class.new("1.2.3pre3")).to be > described_class.new("1.2.3alpha2") expect(described_class.new("1.2.3pre3")).to be > described_class.new("1.2.3alpha4") expect(described_class.new("1.2.3pre3")).to be > described_class.new("1.2.3beta3") expect(described_class.new("1.2.3pre3")).to be > described_class.new("1.2.3beta5") expect(described_class.new("1.2.3pre3")).to be < described_class.new("1.2.3rc2") expect(described_class.new("1.2.3pre3")).to be < described_class.new("1.2.3") expect(described_class.new("1.2.3pre3")).to be < described_class.new("1.2.3-p2") end specify "comparing RC versions" do expect(described_class.new("1.2.3rc3")).to eq described_class.new("1.2.3RC3") expect(described_class.new("1.2.3rc3")).to be > described_class.new("1.2.3rc2") expect(described_class.new("1.2.3rc3")).to be < described_class.new("1.2.3rc4") expect(described_class.new("1.2.3rc3")).to be < described_class.new("1.2.3rc10") expect(described_class.new("1.2.3rc3")).to be > described_class.new("1.2.3alpha4") expect(described_class.new("1.2.3rc3")).to be > described_class.new("1.2.3beta2") expect(described_class.new("1.2.3rc3")).to be < described_class.new("1.2.3") expect(described_class.new("1.2.3rc3")).to be < described_class.new("1.2.3-p34") end specify "comparing patch-level versions" do expect(described_class.new("1.2.3-p34")).to eq described_class.new("1.2.3-P34") expect(described_class.new("1.2.3-p34")).to be > described_class.new("1.2.3-p33") expect(described_class.new("1.2.3-p34")).to be < described_class.new("1.2.3-p35") expect(described_class.new("1.2.3-p34")).to be > described_class.new("1.2.3-p9") expect(described_class.new("1.2.3-p34")).to be > described_class.new("1.2.3alpha4") expect(described_class.new("1.2.3-p34")).to be > described_class.new("1.2.3beta2") expect(described_class.new("1.2.3-p34")).to be > described_class.new("1.2.3rc3") expect(described_class.new("1.2.3-p34")).to be > described_class.new("1.2.3") end specify "comparing post-level versions" do expect(described_class.new("1.2.3.post34")).to be > described_class.new("1.2.3.post33") expect(described_class.new("1.2.3.post34")).to be < described_class.new("1.2.3.post35") expect(described_class.new("1.2.3.post34")).to be > described_class.new("1.2.3rc35") expect(described_class.new("1.2.3.post34")).to be > described_class.new("1.2.3alpha35") expect(described_class.new("1.2.3.post34")).to be > described_class.new("1.2.3beta35") expect(described_class.new("1.2.3.post34")).to be > described_class.new("1.2.3") end specify "comparing unevenly-padded versions" do expect(described_class.new("2.1.0-p194")).to be < described_class.new("2.1-p195") expect(described_class.new("2.1-p195")).to be > described_class.new("2.1.0-p194") expect(described_class.new("2.1-p194")).to be < described_class.new("2.1.0-p195") expect(described_class.new("2.1.0-p195")).to be > described_class.new("2.1-p194") expect(described_class.new("2-p194")).to be < described_class.new("2.1-p195") end it "can be compared against nil" do expect(described_class.new("2.1.0-p194")).to be > nil end it "can be compared against Version::NULL" do expect(described_class.new("2.1.0-p194")).to be > Version::NULL end it "can be compared against strings" do expect(described_class.new("2.1.0-p194")).to eq "2.1.0-p194" expect(described_class.new("1")).to eq 1 end it "can be compared against tokens" do expect(described_class.new("2.1.0-p194")).to be > Version::Token.create("2") expect(described_class.new("1")).to eq Version::Token.create("1") end it "can be compared against Version::NULL_TOKEN" do expect(described_class.new("2.1.0-p194")).to be > Version::NULL_TOKEN end specify "comparison returns nil for non-version" do v = described_class.new("1.0") expect(v <=> Object.new).to be_nil expect { v > Object.new }.to raise_error(ArgumentError) end specify "erlang versions" do versions = %w[R16B R15B03-1 R15B03 R15B02 R15B01 R14B04 R14B03 R14B02 R14B01 R14B R13B04 R13B03 R13B02-1].reverse expect(versions.sort_by { |v| described_class.new(v) }).to eq(versions) end specify "hash equality" do v1 = described_class.new("0.1.0") v2 = described_class.new("0.1.0") v3 = described_class.new("0.1.1") expect(v1).to eql(v2) expect(v1).not_to eql(v3) expect(v1.hash).to eq(v2.hash) expect(v1.hash).not_to eq(v3.hash) h = { v1 => :foo } expect(h[v2]).to eq(:foo) end describe "::new" do it "raises a TypeError for non-string objects" do expect { described_class.new(1.1) }.to raise_error(TypeError) expect { described_class.new(1) }.to raise_error(TypeError) expect { described_class.new(:symbol) }.to raise_error(TypeError) end it "parses a version from a string" do v = described_class.new("1.20") expect(v).not_to be_head expect(v.to_str).to eq("1.20") end specify "HEAD with commit" do v = described_class.new("HEAD-abcdef") expect(v.commit).to eq("abcdef") expect(v.to_str).to eq("HEAD-abcdef") end specify "HEAD without commit" do v = described_class.new("HEAD") expect(v.commit).to be_nil expect(v.to_str).to eq("HEAD") end end describe "#detected_from_url?" do it "is false if created explicitly" do expect(described_class.new("1.0.0")).not_to be_detected_from_url end it "is true if the version was detected from a URL" do version = described_class.detect("https://example.org/archive-1.0.0.tar.gz") expect(version).to eq "1.0.0" expect(version).to be_detected_from_url end end specify "#head?" do v1 = described_class.new("HEAD-abcdef") v2 = described_class.new("HEAD") expect(v1).to be_head expect(v2).to be_head end specify "#update_commit" do v1 = described_class.new("HEAD-abcdef") v2 = described_class.new("HEAD") v1.update_commit("ffffff") expect(v1.commit).to eq("ffffff") expect(v1.to_str).to eq("HEAD-ffffff") v2.update_commit("ffffff") expect(v2.commit).to eq("ffffff") expect(v2.to_str).to eq("HEAD-ffffff") end describe "#major" do it "returns major version token" do expect(described_class.new("1").major).to eq Version::Token.create("1") expect(described_class.new("1.2").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3alpha").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3alpha4").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3beta4").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3pre4").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3rc4").major).to eq Version::Token.create("1") expect(described_class.new("1.2.3-p4").major).to eq Version::Token.create("1") end end describe "#minor" do it "returns minor version token" do expect(described_class.new("1").minor).to be_nil expect(described_class.new("1.2").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3alpha").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3alpha4").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3beta4").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3pre4").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3rc4").minor).to eq Version::Token.create("2") expect(described_class.new("1.2.3-p4").minor).to eq Version::Token.create("2") end end describe "#patch" do it "returns patch version token" do expect(described_class.new("1").patch).to be_nil expect(described_class.new("1.2").patch).to be_nil expect(described_class.new("1.2.3").patch).to eq Version::Token.create("3") expect(described_class.new("1.2.3alpha").patch).to eq Version::Token.create("3") expect(described_class.new("1.2.3alpha4").patch).to eq Version::Token.create("3") expect(described_class.new("1.2.3beta4").patch).to eq Version::Token.create("3") expect(described_class.new("1.2.3pre4").patch).to eq Version::Token.create("3") expect(described_class.new("1.2.3rc4").patch).to eq Version::Token.create("3") expect(described_class.new("1.2.3-p4").patch).to eq Version::Token.create("3") end end describe "#major_minor" do it "returns major.minor version" do expect(described_class.new("1").major_minor).to eq described_class.new("1") expect(described_class.new("1.2").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3alpha").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3alpha4").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3beta4").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3pre4").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3rc4").major_minor).to eq described_class.new("1.2") expect(described_class.new("1.2.3-p4").major_minor).to eq described_class.new("1.2") end end describe "#major_minor_patch" do it "returns major.minor.patch version" do expect(described_class.new("1").major_minor_patch).to eq described_class.new("1") expect(described_class.new("1.2").major_minor_patch).to eq described_class.new("1.2") expect(described_class.new("1.2.3").major_minor_patch).to eq described_class.new("1.2.3") expect(described_class.new("1.2.3alpha").major_minor_patch).to eq described_class.new("1.2.3") expect(described_class.new("1.2.3alpha4").major_minor_patch).to eq described_class.new("1.2.3") expect(described_class.new("1.2.3beta4").major_minor_patch).to eq described_class.new("1.2.3") expect(described_class.new("1.2.3pre4").major_minor_patch).to eq described_class.new("1.2.3") expect(described_class.new("1.2.3rc4").major_minor_patch).to eq described_class.new("1.2.3") expect(described_class.new("1.2.3-p4").major_minor_patch).to eq described_class.new("1.2.3") end end describe "::parse" do it "returns a NULL version when the URL cannot be parsed" do expect(described_class.parse("https://brew.sh/blah.tar")).to be_null expect(described_class.parse("foo")).to be_null end end describe "::detect" do matcher :be_detected_from do |url, **specs| match do |expected| @detected = described_class.detect(url, **specs) @detected == expected end failure_message do |expected| message = <<~EOS expected: %s detected: %s EOS format(message, expected, @detected) end end specify "version all dots" do expect(described_class.new("1.14")) .to be_detected_from("https://brew.sh/foo.bar.la.1.14.zip") end specify "version underscore separator" do expect(described_class.new("1.1")) .to be_detected_from("https://brew.sh/grc_1.1.tar.gz") end specify "boost version style" do expect(described_class.new("1.39.0")) .to be_detected_from("https://brew.sh/boost_1_39_0.tar.bz2") end specify "erlang version style" do expect(described_class.new("R13B")) .to be_detected_from("https://erlang.org/download/otp_src_R13B.tar.gz") end specify "another erlang version style" do expect(described_class.new("R15B01")) .to be_detected_from("https://github.com/erlang/otp/tarball/OTP_R15B01") end specify "yet another erlang version style" do expect(described_class.new("R15B03-1")) .to be_detected_from("https://github.com/erlang/otp/tarball/OTP_R15B03-1") end specify "p7zip version style" do expect(described_class.new("9.04")) .to be_detected_from("https://kent.dl.sourceforge.net/sourceforge/p7zip/p7zip_9.04_src_all.tar.bz2") end specify "new github style" do expect(described_class.new("1.1.4")) .to be_detected_from("https://github.com/sam-github/libnet/tarball/libnet-1.1.4") end specify "codeload style" do expect(described_class.new("0.7.1")) .to be_detected_from("https://codeload.github.com/gsamokovarov/jump/tar.gz/v0.7.1") end specify "gloox beta style" do expect(described_class.new("1.0-beta7")) .to be_detected_from("https://camaya.net/download/gloox-1.0-beta7.tar.bz2") end specify "sphinx beta style" do expect(described_class.new("1.10-beta")) .to be_detected_from("http://sphinxsearch.com/downloads/sphinx-1.10-beta.tar.gz") end specify "astyle version style" do expect(described_class.new("1.23")) .to be_detected_from("https://kent.dl.sourceforge.net/sourceforge/astyle/astyle_1.23_macosx.tar.gz") end specify "version dos2unix" do expect(described_class.new("3.1")) .to be_detected_from("http://www.sfr-fresh.com/linux/misc/dos2unix-3.1.tar.gz") end specify "version internal dash" do expect(described_class.new("1.1-2")) .to be_detected_from("https://brew.sh/foo-arse-1.1-2.tar.gz") expect(described_class.new("3.3.04-1")) .to be_detected_from("https://brew.sh/3.3.04-1.tar.gz") expect(described_class.new("1.2-20200102")) .to be_detected_from("https://brew.sh/v1.2-20200102.tar.gz") expect(described_class.new("3.6.6-0.2")) .to be_detected_from("https://brew.sh/v3.6.6-0.2.tar.gz") end specify "version single digit" do expect(described_class.new("45")) .to be_detected_from("https://brew.sh/foo_bar.45.tar.gz") end specify "noseparator single digit" do expect(described_class.new("45")) .to be_detected_from("https://brew.sh/foo_bar45.tar.gz") end specify "version developer that hates us format" do expect(described_class.new("1.2.3")) .to be_detected_from("https://brew.sh/foo-bar-la.1.2.3.tar.gz") end specify "version regular" do expect(described_class.new("1.21")) .to be_detected_from("https://brew.sh/foo_bar-1.21.tar.gz") end specify "version sourceforge download" do expect(described_class.new("1.21")) .to be_detected_from("https://sourceforge.net/foo_bar-1.21.tar.gz/download") expect(described_class.new("1.21")) .to be_detected_from("https://sf.net/foo_bar-1.21.tar.gz/download") end specify "version github" do expect(described_class.new("1.0.5")) .to be_detected_from("https://github.com/lloyd/yajl/tarball/1.0.5") end specify "version github with high patch number" do expect(described_class.new("1.2.34")) .to be_detected_from("https://github.com/lloyd/yajl/tarball/v1.2.34") end specify "yet another version" do expect(described_class.new("0.15.1b")) .to be_detected_from("https://brew.sh/mad-0.15.1b.tar.gz") end specify "lame version style" do expect(described_class.new("398-2")) .to be_detected_from("https://kent.dl.sourceforge.net/sourceforge/lame/lame-398-2.tar.gz") end specify "ruby version style" do expect(described_class.new("1.9.1-p243")) .to be_detected_from("ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.1-p243.tar.gz") end specify "omega version style" do expect(described_class.new("0.80.2")) .to be_detected_from("http://www.alcyone.com/binaries/omega/omega-0.80.2-src.tar.gz") end specify "rc style" do expect(described_class.new("1.2.2rc1")) .to be_detected_from("https://downloads.xiph.org/releases/vorbis/libvorbis-1.2.2rc1.tar.bz2") end specify "dash rc style" do expect(described_class.new("1.8.0-rc1")) .to be_detected_from("https://ftp.mozilla.org/pub/mozilla.org/js/js-1.8.0-rc1.tar.gz") end specify "angband version style" do expect(described_class.new("3.0.9b")) .to be_detected_from("http://rephial.org/downloads/3.0/angband-3.0.9b-src.tar.gz") end specify "stable suffix" do expect(described_class.new("1.4.14b")) .to be_detected_from("https://www.monkey.org/~provos/libevent-1.4.14b-stable.tar.gz") end specify "debian style" do expect(described_class.new("3.03")) .to be_detected_from("https://ftp.de.debian.org/debian/pool/main/s/sl/sl_3.03.orig.tar.gz") end specify "debian style with letter suffix" do expect(described_class.new("1.01b")) .to be_detected_from("https://ftp.de.debian.org/debian/pool/main/m/mmv/mmv_1.01b.orig.tar.gz") end specify "debian style dotless" do expect(described_class.new("1")) .to be_detected_from("https://deb.debian.org/debian/pool/main/e/example/example_1.orig.tar.gz") expect(described_class.new("20040914")) .to be_detected_from("https://deb.debian.org/debian/pool/main/e/example/example_20040914.orig.tar.gz") end specify "bottle style" do expect(described_class.new("4.8.0")) .to be_detected_from("https://homebrew.bintray.com/bottles/qt-4.8.0.lion.bottle.tar.gz") end specify "versioned bottle style" do expect(described_class.new("4.8.1")) .to be_detected_from("https://homebrew.bintray.com/bottles/qt-4.8.1.lion.bottle.1.tar.gz") end specify "erlang bottle style" do expect(described_class.new("R15B")) .to be_detected_from("https://homebrew.bintray.com/bottles/erlang-R15B.lion.bottle.tar.gz") end specify "another erlang bottle style" do expect(described_class.new("R15B01")) .to be_detected_from("https://homebrew.bintray.com/bottles/erlang-R15B01.mountain_lion.bottle.tar.gz") end specify "yet another erlang bottle style" do expect(described_class.new("R15B03-1")) .to be_detected_from("https://homebrew.bintray.com/bottles/erlang-R15B03-1.mountainlion.bottle.tar.gz") end specify "imagemagick style" do expect(described_class.new("6.7.5-7")) .to be_detected_from("https://downloads.sf.net/project/machomebrew/mirror/ImageMagick-6.7.5-7.tar.bz2") end specify "imagemagick bottle style" do expect(described_class.new("6.7.5-7")) .to be_detected_from("https://homebrew.bintray.com/bottles/imagemagick-6.7.5-7.lion.bottle.tar.gz") end specify "imagemagick versioned bottle style" do expect(described_class.new("6.7.5-7")) .to be_detected_from("https://homebrew.bintray.com/bottles/imagemagick-6.7.5-7.lion.bottle.1.tar.gz") end specify "date-based version style" do expect(described_class.new("2017-04-17")) .to be_detected_from("https://brew.sh/dada-v2017-04-17.tar.gz") end specify "unstable version style" do expect(described_class.new("1.3.0-beta.1")) .to be_detected_from("https://registry.npmjs.org/@angular/cli/-/cli-1.3.0-beta.1.tgz") expect(described_class.new("2.074.0-beta1")) .to be_detected_from("https://github.com/dlang/dmd/archive/v2.074.0-beta1.tar.gz") expect(described_class.new("2.074.0-rc1")) .to be_detected_from("https://github.com/dlang/dmd/archive/v2.074.0-rc1.tar.gz") expect(described_class.new("5.0.0-alpha10")) .to be_detected_from( "https://github.com/premake/premake-core/releases/download/v5.0.0-alpha10/premake-5.0.0-alpha10-src.zip", ) end specify "jenkins version style" do expect(described_class.new("1.486")) .to be_detected_from("https://mirrors.jenkins-ci.org/war/1.486/jenkins.war") expect(described_class.new("0.10.11")) .to be_detected_from("https://github.com/hechoendrupal/DrupalConsole/releases/download/0.10.11/drupal.phar") end specify "char prefixed, url-only version style" do expect(described_class.new("1.9.293")) .to be_detected_from("https://github.com/clojure/clojurescript/releases/download/r1.9.293/cljs.jar") expect(described_class.new("0.6.1")) .to be_detected_from("https://github.com/fibjs/fibjs/releases/download/v0.6.1/fullsrc.zip") expect(described_class.new("1.9")) .to be_detected_from("https://wwwlehre.dhbw-stuttgart.de/~sschulz/WORK/E_DOWNLOAD/V_1.9/E.tgz") end specify "w.x.y.z url-only version style" do expect(described_class.new("2.3.2.0")) .to be_detected_from("https://github.com/JustArchi/ArchiSteamFarm/releases/download/2.3.2.0/ASF.zip") expect(described_class.new("1.7.5.2")) .to be_detected_from("https://people.gnome.org/~newren/eg/download/1.7.5.2/eg") end specify "dash version style" do expect(described_class.new("3.4")) .to be_detected_from("https://www.antlr.org/download/antlr-3.4-complete.jar") expect(described_class.new("9.2")) .to be_detected_from("https://cdn.nuxeo.com/nuxeo-9.2/nuxeo-server-9.2-tomcat.zip") expect(described_class.new("0.181")) .to be_detected_from( "https://search.maven.org/remotecontent?filepath=" \ "com/facebook/presto/presto-cli/0.181/presto-cli-0.181-executable.jar", ) expect(described_class.new("1.2.3")) .to be_detected_from( "https://search.maven.org/remotecontent?filepath=org/apache/orc/orc-tools/1.2.3/orc-tools-1.2.3-uber.jar", ) end specify "apache version style" do expect(described_class.new("1.2.0-rc2")) .to be_detected_from( "https://www.apache.org/dyn/closer.cgi?path=/cassandra/1.2.0/apache-cassandra-1.2.0-rc2-bin.tar.gz", ) end specify "jpeg version style" do expect(described_class.new("8d")) .to be_detected_from("https://www.ijg.org/files/jpegsrc.v8d.tar.gz") end specify "ghc version style" do expect(described_class.new("7.0.4")) .to be_detected_from("https://www.haskell.org/ghc/dist/7.0.4/ghc-7.0.4-x86_64-apple-darwin.tar.bz2") expect(described_class.new("7.0.4")) .to be_detected_from("https://www.haskell.org/ghc/dist/7.0.4/ghc-7.0.4-i386-apple-darwin.tar.bz2") end specify "pypy version style" do expect(described_class.new("1.4.1")) .to be_detected_from("https://pypy.org/download/pypy-1.4.1-osx.tar.bz2") end specify "openssl version style" do expect(described_class.new("0.9.8s")) .to be_detected_from("https://www.openssl.org/source/openssl-0.9.8s.tar.gz") end specify "xaw3d version style" do expect(described_class.new("1.5E")) .to be_detected_from("ftp://ftp.visi.com/users/hawkeyd/X/Xaw3d-1.5E.tar.gz") end specify "assimp version style" do expect(described_class.new("2.0.863")) .to be_detected_from("https://downloads.sourceforge.net/project/assimp/assimp-2.0/assimp--2.0.863-sdk.zip") end specify "cmucl version style" do expect(described_class.new("20c")) .to be_detected_from( "https://common-lisp.net/project/cmucl/downloads/release/20c/cmucl-20c-x86-darwin.tar.bz2", ) end specify "fann version style" do expect(described_class.new("2.1.0beta")) .to be_detected_from("https://downloads.sourceforge.net/project/fann/fann/2.1.0beta/fann-2.1.0beta.zip") end specify "grads version style" do expect(described_class.new("2.0.1")) .to be_detected_from("ftp://iges.org/grads/2.0/grads-2.0.1-bin-darwin9.8-intel.tar.gz") end specify "haxe version style" do expect(described_class.new("2.08"))
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
true
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/dependencies_spec.rb
Library/Homebrew/test/dependencies_spec.rb
# frozen_string_literal: true require "dependencies" require "dependency" RSpec.describe Dependencies do subject(:dependencies) { described_class.new } describe "#<<" do it "returns itself" do expect(dependencies << Dependency.new("foo")).to eq(dependencies) end it "preserves order" do hash = { 0 => "foo", 1 => "bar", 2 => "baz" } dependencies << Dependency.new(hash[0]) dependencies << Dependency.new(hash[1]) dependencies << Dependency.new(hash[2]) dependencies.each_with_index do |dep, i| expect(dep.name).to eq(hash[i]) end end end specify "#*" do dependencies << Dependency.new("foo") dependencies << Dependency.new("bar") expect(dependencies * ", ").to eq("foo, bar") end specify "#to_a" do dep = Dependency.new("foo") dependencies << dep expect(dependencies.to_a).to eq([dep]) end specify "#to_ary" do dep = Dependency.new("foo") dependencies << dep expect(dependencies.to_ary).to eq([dep]) end specify "type helpers" do foo = Dependency.new("foo") bar = Dependency.new("bar", [:optional]) baz = Dependency.new("baz", [:build]) qux = Dependency.new("qux", [:recommended]) quux = Dependency.new("quux") dependencies << foo << bar << baz << qux << quux expect(dependencies.required).to eq([foo, quux]) expect(dependencies.optional).to eq([bar]) expect(dependencies.build).to eq([baz]) expect(dependencies.recommended).to eq([qux]) expect(dependencies.default.sort_by(&:name)).to eq([foo, baz, quux, qux].sort_by(&:name)) end specify "equality" do a = described_class.new b = described_class.new dep = Dependency.new("foo") a << dep b << dep expect(a).to eq(b) expect(a).to eql(b) b << Dependency.new("bar", [:optional]) expect(a).not_to eq(b) expect(a).not_to eql(b) end specify "#empty?" do expect(dependencies).to be_empty dependencies << Dependency.new("foo") expect(dependencies).not_to be_empty end specify "#inspect" do expect(dependencies.inspect).to eq("#<Dependencies: []>") dependencies << Dependency.new("foo") expect(dependencies.inspect).to eq("#<Dependencies: [#<Dependency: \"foo\" []>]>") end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/bump_version_parser_spec.rb
Library/Homebrew/test/bump_version_parser_spec.rb
# frozen_string_literal: true require "bump_version_parser" RSpec.describe Homebrew::BumpVersionParser do let(:general_version) { "1.2.3" } let(:intel_version) { "2.3.4" } let(:arm_version) { "3.4.5" } context "when initializing with no versions" do it "raises a usage error" do expect do described_class.new end.to raise_error(UsageError, "Invalid usage: `--version` must not be empty.") end end context "when initializing with only an intel version" do it "raises a UsageError" do expect do described_class.new(intel: intel_version) end.to raise_error(UsageError, "Invalid usage: `--version-arm` must not be empty.") end end context "when initializing with only an arm version" do it "raises a UsageError" do expect do described_class.new(arm: arm_version) end.to raise_error(UsageError, "Invalid usage: `--version-intel` must not be empty.") end end context "when initializing with arm and intel versions" do let(:new_version_arm_intel) { described_class.new(arm: arm_version, intel: intel_version) } it "correctly parses arm and intel versions" do expect(new_version_arm_intel.arm).to eq(Cask::DSL::Version.new(arm_version.to_s)) expect(new_version_arm_intel.intel).to eq(Cask::DSL::Version.new(intel_version.to_s)) end end context "when initializing with all versions" do let(:new_version) { described_class.new(general: general_version, arm: arm_version, intel: intel_version) } let(:new_version_version) do described_class.new( general: Version.new(general_version), arm: Version.new(arm_version), intel: Version.new(intel_version), ) end it "correctly parses general version" do expect(new_version.general).to eq(Cask::DSL::Version.new(general_version.to_s)) expect(new_version_version.general).to eq(Cask::DSL::Version.new(general_version.to_s)) end it "correctly parses arm version" do # rubocop:todo RSpec/AggregateExamples expect(new_version.arm).to eq(Cask::DSL::Version.new(arm_version.to_s)) expect(new_version_version.arm).to eq(Cask::DSL::Version.new(arm_version.to_s)) end it "correctly parses intel version" do # rubocop:todo RSpec/AggregateExamples expect(new_version.intel).to eq(Cask::DSL::Version.new(intel_version.to_s)) expect(new_version_version.intel).to eq(Cask::DSL::Version.new(intel_version.to_s)) end context "when the version is latest" do it "returns a version object for latest" do new_version = described_class.new(general: "latest") expect(new_version.general.to_s).to eq("latest") end context "when the version is not latest" do it "returns a version object for the given version" do new_version = described_class.new(general: general_version) expect(new_version.general.to_s).to eq(general_version) end end end context "when checking if VersionParser is blank" do it "returns false if any version is present" do new_version = described_class.new(general: general_version.to_s, arm: "", intel: "") expect(new_version.blank?).to be(false) end end end describe "#==" do let(:new_version) { described_class.new(general: general_version, arm: arm_version, intel: intel_version) } context "when other object is not a `BumpVersionParser`" do it "returns false" do expect(new_version == Version.new("1.2.3")).to be(false) end end context "when comparing objects with equal versions" do it "returns true" do same_version = described_class.new(general: general_version, arm: arm_version, intel: intel_version) expect(new_version == same_version).to be(true) end end context "when comparing objects with different versions" do it "returns false" do different_general_version = described_class.new(general: "3.2.1", arm: arm_version, intel: intel_version) different_arm_version = described_class.new(general: general_version, arm: "4.3.2", intel: intel_version) different_intel_version = described_class.new(general: general_version, arm: arm_version, intel: "5.4.3") different_general_arm_versions = described_class.new(general: "3.2.1", arm: "4.3.2", intel: intel_version) different_arm_intel_versions = described_class.new(general: general_version, arm: "4.3.2", intel: "5.4.3") different_general_intel_versions = described_class.new(general: "3.2.1", arm: arm_version, intel: "5.4.3") expect(new_version == different_general_version).to be(false) expect(new_version == different_arm_version).to be(false) expect(new_version == different_intel_version).to be(false) expect(new_version == different_general_arm_versions).to be(false) expect(new_version == different_arm_intel_versions).to be(false) expect(new_version == different_general_intel_versions).to be(false) end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/test_runner_formula_spec.rb
Library/Homebrew/test/test_runner_formula_spec.rb
# frozen_string_literal: true require "test_runner_formula" require "test/support/fixtures/testball" RSpec.describe TestRunnerFormula do let(:testball) { Testball.new } let(:xcode_helper) { setup_test_runner_formula("xcode-helper", [:macos]) } let(:linux_kernel_requirer) { setup_test_runner_formula("linux-kernel-requirer", [:linux]) } let(:old_non_portable_software) { setup_test_runner_formula("old-non-portable-software", [arch: :x86_64]) } let(:fancy_new_software) { setup_test_runner_formula("fancy-new-software", [arch: :arm64]) } let(:needs_modern_compiler) { setup_test_runner_formula("needs-modern-compiler", [macos: :ventura]) } describe "#initialize" do it "enables the Formulary factory cache" do described_class.new(testball) expect(Formulary.factory_cached?).to be(true) end end describe "#name" do it "returns the wrapped Formula's name" do expect(described_class.new(testball).name).to eq(testball.name) end end describe "#eval_all" do it "is false by default" do expect(described_class.new(testball).eval_all).to be(false) end it "can be instantiated to be `true`" do # rubocop:todo RSpec/AggregateExamples expect(described_class.new(testball, eval_all: true).eval_all).to be(true) end it "takes the value of HOMEBREW_EVAL_ALL at instantiation time if not specified" do allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true) expect(described_class.new(testball).eval_all).to be(true) allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(false) expect(described_class.new(testball).eval_all).to be(false) end end describe "#formula" do it "returns the wrapped Formula" do expect(described_class.new(testball).formula).to eq(testball) end end describe "#macos_only?" do context "when a formula requires macOS" do it "returns true" do expect(described_class.new(xcode_helper).macos_only?).to be(true) end end context "when a formula does not require macOS" do it "returns false" do expect(described_class.new(testball).macos_only?).to be(false) expect(described_class.new(linux_kernel_requirer).macos_only?).to be(false) expect(described_class.new(old_non_portable_software).macos_only?).to be(false) expect(described_class.new(fancy_new_software).macos_only?).to be(false) end end context "when a formula requires only a minimum version of macOS" do it "returns false" do expect(described_class.new(needs_modern_compiler).macos_only?).to be(false) end end end describe "#macos_compatible?" do context "when a formula is compatible with macOS" do it "returns true" do expect(described_class.new(testball).macos_compatible?).to be(true) expect(described_class.new(xcode_helper).macos_compatible?).to be(true) expect(described_class.new(old_non_portable_software).macos_compatible?).to be(true) expect(described_class.new(fancy_new_software).macos_compatible?).to be(true) end end context "when a formula requires only a minimum version of macOS" do it "returns false" do expect(described_class.new(needs_modern_compiler).macos_compatible?).to be(true) end end context "when a formula is not compatible with macOS" do it "returns false" do expect(described_class.new(linux_kernel_requirer).macos_compatible?).to be(false) end end end describe "#linux_only?" do context "when a formula requires Linux" do it "returns true" do expect(described_class.new(linux_kernel_requirer).linux_only?).to be(true) end end context "when a formula does not require Linux" do it "returns false" do expect(described_class.new(testball).linux_only?).to be(false) expect(described_class.new(xcode_helper).linux_only?).to be(false) expect(described_class.new(old_non_portable_software).linux_only?).to be(false) expect(described_class.new(fancy_new_software).linux_only?).to be(false) expect(described_class.new(needs_modern_compiler).linux_only?).to be(false) end end end describe "#linux_compatible?" do context "when a formula is compatible with Linux" do it "returns true" do expect(described_class.new(testball).linux_compatible?).to be(true) expect(described_class.new(linux_kernel_requirer).linux_compatible?).to be(true) expect(described_class.new(old_non_portable_software).linux_compatible?).to be(true) expect(described_class.new(fancy_new_software).linux_compatible?).to be(true) expect(described_class.new(needs_modern_compiler).linux_compatible?).to be(true) end end context "when a formula is not compatible with Linux" do it "returns false" do expect(described_class.new(xcode_helper).linux_compatible?).to be(false) end end end describe "#x86_64_only?" do context "when a formula requires an Intel architecture" do it "returns true" do expect(described_class.new(old_non_portable_software).x86_64_only?).to be(true) end end context "when a formula requires a non-Intel architecture" do it "returns false" do expect(described_class.new(fancy_new_software).x86_64_only?).to be(false) end end context "when a formula does not require a specific architecture" do it "returns false" do expect(described_class.new(testball).x86_64_only?).to be(false) expect(described_class.new(xcode_helper).x86_64_only?).to be(false) expect(described_class.new(linux_kernel_requirer).x86_64_only?).to be(false) expect(described_class.new(needs_modern_compiler).x86_64_only?).to be(false) end end end describe "#x86_64_compatible?" do context "when a formula is compatible with the Intel architecture" do it "returns true" do expect(described_class.new(testball).x86_64_compatible?).to be(true) expect(described_class.new(xcode_helper).x86_64_compatible?).to be(true) expect(described_class.new(linux_kernel_requirer).x86_64_compatible?).to be(true) expect(described_class.new(old_non_portable_software).x86_64_compatible?).to be(true) expect(described_class.new(needs_modern_compiler).x86_64_compatible?).to be(true) end end context "when a formula is not compatible with the Intel architecture" do it "returns false" do expect(described_class.new(fancy_new_software).x86_64_compatible?).to be(false) end end end describe "#arm64_only?" do context "when a formula requires an ARM64 architecture" do it "returns true" do expect(described_class.new(fancy_new_software).arm64_only?).to be(true) end end context "when a formula requires a non-ARM64 architecture" do it "returns false" do expect(described_class.new(old_non_portable_software).arm64_only?).to be(false) end end context "when a formula does not require a specific architecture" do it "returns false" do expect(described_class.new(testball).arm64_only?).to be(false) expect(described_class.new(xcode_helper).arm64_only?).to be(false) expect(described_class.new(linux_kernel_requirer).arm64_only?).to be(false) expect(described_class.new(needs_modern_compiler).arm64_only?).to be(false) end end end describe "#arm64_compatible?" do context "when a formula is compatible with an ARM64 architecture" do it "returns true" do expect(described_class.new(testball).arm64_compatible?).to be(true) expect(described_class.new(xcode_helper).arm64_compatible?).to be(true) expect(described_class.new(linux_kernel_requirer).arm64_compatible?).to be(true) expect(described_class.new(fancy_new_software).arm64_compatible?).to be(true) expect(described_class.new(needs_modern_compiler).arm64_compatible?).to be(true) end end context "when a formula is not compatible with an ARM64 architecture" do it "returns false" do expect(described_class.new(old_non_portable_software).arm64_compatible?).to be(false) end end end describe "#versioned_macos_requirement" do let(:requirement) { described_class.new(needs_modern_compiler).versioned_macos_requirement } it "returns a MacOSRequirement with a specified version" do expect(requirement).to be_a(MacOSRequirement) expect(requirement.version_specified?).to be(true) end context "when a formula has an unversioned MacOSRequirement" do it "returns nil" do expect(described_class.new(xcode_helper).versioned_macos_requirement).to be_nil end end context "when a formula has no declared MacOSRequirement" do it "returns nil" do expect(described_class.new(testball).versioned_macos_requirement).to be_nil expect(described_class.new(linux_kernel_requirer).versioned_macos_requirement).to be_nil expect(described_class.new(old_non_portable_software).versioned_macos_requirement).to be_nil expect(described_class.new(fancy_new_software).versioned_macos_requirement).to be_nil end end end describe "#compatible_with?" do context "when a formula has a versioned MacOSRequirement" do context "when passed a compatible macOS version" do it "returns true" do expect(described_class.new(needs_modern_compiler).compatible_with?(MacOSVersion.new("13"))) .to be(true) end end context "when passed an incompatible macOS version" do it "returns false" do expect(described_class.new(needs_modern_compiler).compatible_with?(MacOSVersion.new("11"))) .to be(false) end end end context "when a formula has an unversioned MacOSRequirement" do it "returns true" do MacOSVersion::SYMBOLS.each_value do |v| version = MacOSVersion.new(v) expect(described_class.new(xcode_helper).compatible_with?(version)).to be(true) end end end context "when a formula has no declared MacOSRequirement" do it "returns true" do MacOSVersion::SYMBOLS.each_value do |v| version = MacOSVersion.new(v) expect(described_class.new(testball).compatible_with?(version)).to be(true) expect(described_class.new(linux_kernel_requirer).compatible_with?(version)).to be(true) expect(described_class.new(old_non_portable_software).compatible_with?(version)).to be(true) expect(described_class.new(fancy_new_software).compatible_with?(version)).to be(true) end end end end describe "#dependents" do let(:current_system) do current_arch = case Homebrew::SimulateSystem.current_arch when :arm then :arm64 when :intel then :x86_64 end current_platform = case Homebrew::SimulateSystem.current_os when :generic then :linux else Homebrew::SimulateSystem.current_os end { platform: current_platform, arch: current_arch, macos_version: nil, } end context "when a formula has no dependents" do it "returns an empty array" do expect(described_class.new(testball).dependents(**current_system)).to eq([]) expect(described_class.new(xcode_helper).dependents(**current_system)).to eq([]) expect(described_class.new(linux_kernel_requirer).dependents(**current_system)).to eq([]) expect(described_class.new(old_non_portable_software).dependents(**current_system)).to eq([]) expect(described_class.new(fancy_new_software).dependents(**current_system)).to eq([]) expect(described_class.new(needs_modern_compiler).dependents(**current_system)).to eq([]) end end context "when a formula has dependents" do let(:testball_user) { setup_test_runner_formula("testball_user", ["testball"]) } let(:recursive_testball_dependent) do setup_test_runner_formula("recursive_testball_dependent", ["testball_user"]) end it "returns an array of direct dependents" do allow(Formula).to receive(:all).and_return([testball_user, recursive_testball_dependent]) expect( described_class.new(testball, eval_all: true).dependents(**current_system).map(&:name), ).to eq(["testball_user"]) expect( described_class.new(testball_user, eval_all: true).dependents(**current_system).map(&:name), ).to eq(["recursive_testball_dependent"]) end context "when called with arguments" do let(:testball_user_intel) { setup_test_runner_formula("testball_user-intel", intel: ["testball"]) } let(:testball_user_arm) { setup_test_runner_formula("testball_user-arm", arm: ["testball"]) } let(:testball_user_macos) { setup_test_runner_formula("testball_user-macos", macos: ["testball"]) } let(:testball_user_linux) { setup_test_runner_formula("testball_user-linux", linux: ["testball"]) } let(:testball_user_ventura) do setup_test_runner_formula("testball_user-ventura", ventura: ["testball"]) end let(:testball_and_dependents) do [ testball_user, testball_user_intel, testball_user_arm, testball_user_macos, testball_user_linux, testball_user_ventura, ] end context "when given { platform: :linux, arch: :x86_64 }" do it "returns only the dependents for the requested platform and architecture" do allow(Formula).to receive(:all).and_wrap_original { testball_and_dependents } expect( described_class.new(testball, eval_all: true).dependents( platform: :linux, arch: :x86_64, macos_version: nil, ).map(&:name).sort, ).to eq(["testball_user", "testball_user-intel", "testball_user-linux"].sort) end end context "when given { platform: :macos, arch: :x86_64 }" do it "returns only the dependents for the requested platform and architecture" do allow(Formula).to receive(:all).and_wrap_original { testball_and_dependents } expect( described_class.new(testball, eval_all: true).dependents( platform: :macos, arch: :x86_64, macos_version: nil, ).map(&:name).sort, ).to eq(["testball_user", "testball_user-intel", "testball_user-macos"].sort) end end context "when given `{ platform: :macos, arch: :arm64 }`" do it "returns only the dependents for the requested platform and architecture" do allow(Formula).to receive(:all).and_wrap_original { testball_and_dependents } expect( described_class.new(testball, eval_all: true).dependents( platform: :macos, arch: :arm64, macos_version: nil, ).map(&:name).sort, ).to eq(["testball_user", "testball_user-arm", "testball_user-macos"].sort) end end context "when given `{ platform: :macos, arch: :x86_64, macos_version: :sonoma }`" do it "returns only the dependents for the requested platform and architecture" do allow(Formula).to receive(:all).and_wrap_original { testball_and_dependents } expect( described_class.new(testball, eval_all: true).dependents( platform: :macos, arch: :x86_64, macos_version: :sonoma, ).map(&:name).sort, ).to eq(["testball_user", "testball_user-intel", "testball_user-macos"].sort) end end context "when given `{ platform: :macos, arch: :arm64, macos_version: :ventura }`" do it "returns only the dependents for the requested platform and architecture" do allow(Formula).to receive(:all).and_wrap_original { testball_and_dependents } expect( described_class.new(testball, eval_all: true).dependents( platform: :macos, arch: :arm64, macos_version: :ventura, ).map(&:name).sort, ).to eq(%w[testball_user testball_user-arm testball_user-macos testball_user-ventura].sort) end end end end end def setup_test_runner_formula(name, dependencies = [], **kwargs) formula name do url "https://brew.sh/#{name}-1.0.tar.gz" dependencies.each { |dependency| depends_on dependency } kwargs.each do |k, v| send(:"on_#{k}") do v.each do |dep| depends_on dep 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/test/completions_spec.rb
Library/Homebrew/test/completions_spec.rb
# frozen_string_literal: true require "completions" RSpec.describe Homebrew::Completions do let(:completions_dir) { HOMEBREW_REPOSITORY/"completions" } let(:internal_path) { HOMEBREW_REPOSITORY/"Library/Taps/homebrew/homebrew-bar" } let(:external_path) { HOMEBREW_REPOSITORY/"Library/Taps/foo/homebrew-bar" } before do HOMEBREW_REPOSITORY.cd do system "git", "init" end described_class::SHELLS.each do |shell| (completions_dir/shell).mkpath end internal_path.mkpath external_path.mkpath end after do FileUtils.rm_rf completions_dir FileUtils.rm_rf internal_path FileUtils.rm_rf external_path.dirname end context "when linking or unlinking completions" do def setup_completions(external:) internal_bash_completion = internal_path/"completions/bash" external_bash_completion = external_path/"completions/bash" internal_bash_completion.mkpath (internal_bash_completion/"foo_internal").write "#foo completions" if external external_bash_completion.mkpath (external_bash_completion/"foo_external").write "#foo completions" elsif (external_bash_completion/"foo_external").exist? (external_bash_completion/"foo_external").delete end end def setup_completions_setting(state, setting: "linkcompletions") HOMEBREW_REPOSITORY.cd do system "git", "config", "--replace-all", "homebrew.#{setting}", state.to_s end end def read_completions_setting(setting: "linkcompletions") HOMEBREW_REPOSITORY.cd do Utils.popen_read("git", "config", "--get", "homebrew.#{setting}").chomp.presence end end def delete_completions_setting(setting: "linkcompletions") HOMEBREW_REPOSITORY.cd do system "git", "config", "--unset-all", "homebrew.#{setting}" end end describe ".link!" do it "sets homebrew.linkcompletions to true" do setup_completions_setting false expect { described_class.link! }.not_to raise_error expect(read_completions_setting).to eq "true" end it "sets homebrew.linkcompletions to true if unset" do delete_completions_setting expect { described_class.link! }.not_to raise_error expect(read_completions_setting).to eq "true" end it "keeps homebrew.linkcompletions set to true" do setup_completions_setting true expect { described_class.link! }.not_to raise_error expect(read_completions_setting).to eq "true" end end describe ".unlink!" do it "sets homebrew.linkcompletions to false" do setup_completions_setting true expect { described_class.unlink! }.not_to raise_error expect(read_completions_setting).to eq "false" end it "sets homebrew.linkcompletions to false if unset" do delete_completions_setting expect { described_class.unlink! }.not_to raise_error expect(read_completions_setting).to eq "false" end it "keeps homebrew.linkcompletions set to false" do setup_completions_setting false expect { described_class.unlink! }.not_to raise_error expect(read_completions_setting).to eq "false" end end describe ".link_completions?" do it "returns true if homebrew.linkcompletions is true" do setup_completions_setting true expect(described_class.link_completions?).to be true end it "returns false if homebrew.linkcompletions is false" do setup_completions_setting false expect(described_class.link_completions?).to be false end it "returns false if homebrew.linkcompletions is not set" do expect(described_class.link_completions?).to be false end end describe ".completions_to_link?" do it "returns false if only internal taps have completions" do setup_completions external: false expect(described_class.completions_to_link?).to be false end it "returns true if external taps have completions" do setup_completions external: true expect(described_class.completions_to_link?).to be true end end describe ".show_completions_message_if_needed" do it "doesn't show the message if there are no completions to link" do setup_completions external: false delete_completions_setting setting: :completionsmessageshown expect { described_class.show_completions_message_if_needed }.not_to output.to_stdout end it "doesn't show the message if there are completions to link but the message has already been shown" do setup_completions external: true setup_completions_setting true, setting: :completionsmessageshown expect { described_class.show_completions_message_if_needed }.not_to output.to_stdout end it "shows the message if there are completions to link and the message hasn't already been shown" do setup_completions external: true delete_completions_setting setting: :completionsmessageshown message = /Homebrew completions for external commands are unlinked by default!/ expect { described_class.show_completions_message_if_needed } .to output(message).to_stdout end end end context "when generating completions" do # TODO: re-enable this test if it can be made to take ~ 1 second or there's # an actual regression. # describe ".update_shell_completions!" do # it "generates shell completions" do # described_class.update_shell_completions! # expect(completions_dir/"bash/brew").to be_a_file # end # end describe ".format_description" do it "escapes single quotes" do expect(described_class.format_description("Homebrew's")).to eq "Homebrew'\\''s" end it "escapes single quotes for fish" do expect(described_class.format_description("Homebrew's", fish: true)).to eq "Homebrew\\'s" end it "removes angle brackets" do expect(described_class.format_description("<formula>")).to eq "formula" end it "replaces newlines with spaces" do expect(described_class.format_description("Homebrew\ncommand")).to eq "Homebrew command" end it "removes trailing period" do expect(described_class.format_description("Homebrew.")).to eq "Homebrew" end end describe ".command_options" do it "returns an array of options for a ruby command" do expected_options = { "--debug" => "Display any debugging information.", "--help" => "Show this message.", "--hide" => "Act as if none of the specified <hidden> are installed. <hidden> should be " \ "a comma-separated list of formulae.", "--quiet" => "Make some output more quiet.", "--verbose" => "Make some output more verbose.", } expect(described_class.command_options("missing")).to eq expected_options end it "returns an array of options for a shell command" do expected_options = { "--auto-update" => "Run on auto-updates (e.g. before `brew install`). Skips some slower steps.", "--debug" => "Display a trace of all shell commands as they are executed.", "--force" => "Always do a slower, full update check (even if unnecessary).", "--help" => "Show this message.", "--merge" => "Use `git merge` to apply updates (rather than `git rebase`).", "--quiet" => "Make some output more quiet.", "--verbose" => "Print the directories checked and `git` operations performed.", } expect(described_class.command_options("update")).to eq expected_options end it "handles --[no]- options correctly" do options = described_class.command_options("audit") expect(options.key?("--signing")).to be true expect(options.key?("--no-signing")).to be true expect(options["--signing"] == options["--no-signing"]).to be true end it "return an empty array if command is not found" do expect(described_class.command_options("foobar")).to eq({}) end it "return an empty array for a command with no options" do expect(described_class.command_options("help")).to eq({}) end it "overrides global options with local descriptions" do options = described_class.command_options("upgrade") expect(options["--verbose"]).to eq "Print the verification and post-install steps." end end describe ".command_gets_completions?" do it "returns true for a non-cask command with options" do expect(described_class.command_gets_completions?("install")).to be true end it "returns false for a non-cask command with no options" do expect(described_class.command_gets_completions?("help")).to be false end it "returns false for a cask command" do expect(described_class.command_gets_completions?("cask install")).to be false end end describe ".generate_bash_subcommand_completion" do it "returns nil if completions aren't needed" do expect(described_class.generate_bash_subcommand_completion("help")).to be_nil end it "returns appropriate completion for a ruby command" do completion = described_class.generate_bash_subcommand_completion("missing") expect(completion).to eq <<~COMPLETION _brew_missing() { local cur="${COMP_WORDS[COMP_CWORD]}" case "${cur}" in -*) __brewcomp " --debug --help --hide --quiet --verbose " return ;; *) ;; esac __brew_complete_formulae } COMPLETION end it "returns appropriate completion for a shell command" do completion = described_class.generate_bash_subcommand_completion("update") expect(completion).to eq <<~COMPLETION _brew_update() { local cur="${COMP_WORDS[COMP_CWORD]}" case "${cur}" in -*) __brewcomp " --auto-update --debug --force --help --merge --quiet --verbose " return ;; *) ;; esac } COMPLETION end it "returns appropriate completion for a command with multiple named arg types" do completion = described_class.generate_bash_subcommand_completion("upgrade") expect(completion).to match(/__brew_complete_installed_formulae\n __brew_complete_installed_casks\n}$/) end end describe ".generate_bash_completion_file" do it "returns the correct completion file" do file = described_class.generate_bash_completion_file(%w[install missing update]) expect(file).to match(/^__brewcomp\(\) {$/) expect(file).to match(/^_brew_install\(\) {$/) expect(file).to match(/^_brew_missing\(\) {$/) expect(file).to match(/^_brew_update\(\) {$/) expect(file).to match(/^_brew\(\) {$/) expect(file).to match(/^ {4}install\) _brew_install ;;/) expect(file).to match(/^ {4}missing\) _brew_missing ;;/) expect(file).to match(/^ {4}update\) _brew_update ;;/) expect(file).to match(/^complete -o bashdefault -o default -F _brew brew$/) end end describe ".generate_zsh_subcommand_completion" do it "returns nil if completions aren't needed" do expect(described_class.generate_zsh_subcommand_completion("help")).to be_nil end it "returns appropriate completion for a ruby command" do completion = described_class.generate_zsh_subcommand_completion("missing") expect(completion).to eq <<~COMPLETION # brew missing _brew_missing() { _arguments \\ '--debug[Display any debugging information]' \\ '--help[Show this message]' \\ '--hide[Act as if none of the specified hidden are installed. hidden should be a comma-separated list of formulae]' \\ '--quiet[Make some output more quiet]' \\ '--verbose[Make some output more verbose]' \\ - formula \\ '*:formula:__brew_formulae' } COMPLETION end it "returns appropriate completion for a shell command" do completion = described_class.generate_zsh_subcommand_completion("update") expect(completion).to eq <<~COMPLETION # brew update _brew_update() { _arguments \\ '--auto-update[Run on auto-updates (e.g. before `brew install`). Skips some slower steps]' \\ '--debug[Display a trace of all shell commands as they are executed]' \\ '--force[Always do a slower, full update check (even if unnecessary)]' \\ '--help[Show this message]' \\ '--merge[Use `git merge` to apply updates (rather than `git rebase`)]' \\ '--quiet[Make some output more quiet]' \\ '--verbose[Print the directories checked and `git` operations performed]' } COMPLETION end it "returns appropriate completion for a command with multiple named arg types" do completion = described_class.generate_zsh_subcommand_completion("livecheck") expect(completion).to match( /'*:formula:__brew_formulae'/, ) expect(completion).to match( /'*:cask:__brew_casks'\n}$/, ) end end describe ".generate_zsh_completion_file" do it "returns the correct completion file" do file = described_class.generate_zsh_completion_file(%w[install missing update]) expect(file).to match(/^__brew_list_aliases\(\) {$/) expect(file).to match(/^ up update$/) expect(file).to match(/^__brew_internal_commands\(\) {$/) expect(file).to match(/^ 'install:Install a formula or cask'$/) expect(file).to match(/^ 'missing:Check the given formula kegs for missing dependencies'$/) expect(file).to match(/^ 'update:Fetch the newest version of Homebrew and all formulae from GitHub .*'$/) expect(file).to match(/^_brew_install\(\) {$/) expect(file).to match(/^_brew_missing\(\) {$/) expect(file).to match(/^_brew_update\(\) {$/) expect(file).to match(/^_brew "\$@"$/) end end describe ".generate_fish_subcommand_completion" do it "returns nil if completions aren't needed" do expect(described_class.generate_fish_subcommand_completion("help")).to be_nil end it "returns appropriate completion for a ruby command" do completion = described_class.generate_fish_subcommand_completion("missing") expect(completion).to eq <<~COMPLETION __fish_brew_complete_cmd 'missing' 'Check the given formula kegs for missing dependencies' __fish_brew_complete_arg 'missing' -l debug -d 'Display any debugging information' __fish_brew_complete_arg 'missing' -l help -d 'Show this message' __fish_brew_complete_arg 'missing' -l hide -d 'Act as if none of the specified hidden are installed. hidden should be a comma-separated list of formulae' __fish_brew_complete_arg 'missing' -l quiet -d 'Make some output more quiet' __fish_brew_complete_arg 'missing' -l verbose -d 'Make some output more verbose' __fish_brew_complete_arg 'missing' -a '(__fish_brew_suggest_formulae_all)' COMPLETION end it "returns appropriate completion for a shell command" do completion = described_class.generate_fish_subcommand_completion("update") expect(completion).to eq <<~COMPLETION __fish_brew_complete_cmd 'update' 'Fetch the newest version of Homebrew and all formulae from GitHub using `git`(1) and perform any necessary migrations' __fish_brew_complete_arg 'update' -l auto-update -d 'Run on auto-updates (e.g. before `brew install`). Skips some slower steps' __fish_brew_complete_arg 'update' -l debug -d 'Display a trace of all shell commands as they are executed' __fish_brew_complete_arg 'update' -l force -d 'Always do a slower, full update check (even if unnecessary)' __fish_brew_complete_arg 'update' -l help -d 'Show this message' __fish_brew_complete_arg 'update' -l merge -d 'Use `git merge` to apply updates (rather than `git rebase`)' __fish_brew_complete_arg 'update' -l quiet -d 'Make some output more quiet' __fish_brew_complete_arg 'update' -l verbose -d 'Print the directories checked and `git` operations performed' COMPLETION end it "returns appropriate completion for a command with multiple named arg types" do completion = described_class.generate_fish_subcommand_completion("upgrade") expected_line_start = "__fish_brew_complete_arg 'upgrade; and not __fish_seen_argument" expect(completion).to match( /#{expected_line_start} -l cask -l casks' -a '\(__fish_brew_suggest_formulae_installed\)'/, ) expect(completion).to match( /#{expected_line_start} -l formula -l formulae' -a '\(__fish_brew_suggest_casks_installed\)'/, ) end end describe ".generate_fish_completion_file" do it "returns the correct completion file" do file = described_class.generate_fish_completion_file(%w[install missing update]) expect(file).to match(/^function __fish_brew_complete_cmd/) expect(file).to match(/^__fish_brew_complete_cmd 'install' 'Install a formula or cask'$/) expect(file).to match(/^__fish_brew_complete_cmd 'missing' 'Check the given formula kegs for .*'$/) expect(file).to match(/^__fish_brew_complete_cmd 'update' 'Fetch the newest version of Homebrew .*'$/) end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/deprecate_disable_spec.rb
Library/Homebrew/test/deprecate_disable_spec.rb
# frozen_string_literal: true require "deprecate_disable" RSpec.describe DeprecateDisable do let(:deprecate_date) { Date.parse("2020-01-01") } let(:disable_date) { deprecate_date >> DeprecateDisable::REMOVE_DISABLED_TIME_WINDOW } let(:deprecated_formula) do instance_double(Formula, deprecated?: true, disabled?: false, deprecation_reason: :does_not_build, deprecation_replacement_formula: nil, deprecation_replacement_cask: nil, deprecation_date: nil, disable_date: nil) end let(:deprecated_formula_with_date) do instance_double(Formula, deprecated?: true, disabled?: false, deprecation_reason: :does_not_build, deprecation_replacement_formula: nil, deprecation_replacement_cask: nil, deprecation_date: deprecate_date, disable_date: nil) end let(:disabled_formula) do instance_double(Formula, deprecated?: false, disabled?: true, disable_reason: "is broken", deprecation_replacement_formula: nil, deprecation_replacement_cask: nil, disable_replacement_formula: nil, disable_replacement_cask: nil, deprecation_date: nil, disable_date: nil) end let(:disabled_formula_with_date) do instance_double(Formula, deprecated?: false, disabled?: true, disable_reason: :does_not_build, deprecation_replacement_formula: nil, deprecation_replacement_cask: nil, disable_replacement_formula: nil, disable_replacement_cask: nil, deprecation_date: nil, disable_date: disable_date) end let(:deprecated_cask) do instance_double(Cask::Cask, deprecated?: true, disabled?: false, deprecation_reason: :discontinued, deprecation_replacement_formula: nil, deprecation_replacement_cask: nil, deprecation_date: nil, disable_date: nil) end let(:disabled_cask) do instance_double(Cask::Cask, deprecated?: false, disabled?: true, disable_reason: nil, deprecation_replacement_formula: nil, deprecation_replacement_cask: nil, disable_replacement_formula: nil, disable_replacement_cask: nil, deprecation_date: nil, disable_date: nil) end let(:deprecated_formula_with_replacement) do instance_double(Formula, deprecated?: true, disabled?: false, deprecation_reason: :does_not_build, deprecation_date: nil, disable_date: nil) end let(:disabled_formula_with_replacement) do instance_double(Formula, deprecated?: false, disabled?: true, disable_reason: "is broken", deprecation_date: nil, disable_date: nil) end let(:deprecated_cask_with_replacement) do instance_double(Cask::Cask, deprecated?: true, disabled?: false, deprecation_reason: :discontinued, deprecation_date: nil, disable_date: nil) end let(:disabled_cask_with_replacement) do instance_double(Cask::Cask, deprecated?: false, disabled?: true, disable_reason: nil, deprecation_date: nil, disable_date: nil) end before do formulae = [ deprecated_formula, deprecated_formula_with_date, disabled_formula, disabled_formula_with_date, deprecated_formula_with_replacement, disabled_formula_with_replacement, ] casks = [ deprecated_cask, disabled_cask, deprecated_cask_with_replacement, disabled_cask_with_replacement, ] formulae.each do |f| allow(f).to receive(:is_a?).with(Formula).and_return(true) allow(f).to receive(:is_a?).with(Cask::Cask).and_return(false) end casks.each do |c| allow(c).to receive(:is_a?).with(Formula).and_return(false) allow(c).to receive(:is_a?).with(Cask::Cask).and_return(true) end end describe "::type" do it "returns :deprecated if the formula is deprecated" do expect(described_class.type(deprecated_formula)).to eq :deprecated end it "returns :disabled if the formula is disabled" do expect(described_class.type(disabled_formula)).to eq :disabled end it "returns :deprecated if the cask is deprecated" do expect(described_class.type(deprecated_cask)).to eq :deprecated end it "returns :disabled if the cask is disabled" do expect(described_class.type(disabled_cask)).to eq :disabled end end describe "::message" do it "returns a deprecation message with a preset formula reason" do expect(described_class.message(deprecated_formula)) .to eq "deprecated because it does not build!" end it "returns a deprecation message with disable date" do allow(Date).to receive(:today).and_return(deprecate_date + 1) expect(described_class.message(deprecated_formula_with_date)) .to eq "deprecated because it does not build! It will be disabled on #{disable_date}." end it "returns a disable message with a custom reason" do expect(described_class.message(disabled_formula)) .to eq "disabled because it is broken!" end it "returns a disable message with disable date" do expect(described_class.message(disabled_formula_with_date)) .to eq "disabled because it does not build! It was disabled on #{disable_date}." end it "returns a deprecation message with a preset cask reason" do expect(described_class.message(deprecated_cask)) .to eq "deprecated because it is discontinued upstream!" end it "returns a deprecation message with no reason" do expect(described_class.message(disabled_cask)) .to eq "disabled!" end it "returns a replacement formula message for a deprecated formula" do allow(deprecated_formula_with_replacement).to receive_messages(deprecation_replacement_formula: "foo", deprecation_replacement_cask: nil) expect(described_class.message(deprecated_formula_with_replacement)) .to eq "deprecated because it does not build!\nReplacement:\n brew install --formula foo\n" end it "returns a replacement cask message for a deprecated formula" do allow(deprecated_formula_with_replacement).to receive_messages(deprecation_replacement_formula: nil, deprecation_replacement_cask: "foo") expect(described_class.message(deprecated_formula_with_replacement)) .to eq "deprecated because it does not build!\nReplacement:\n brew install --cask foo\n" end it "returns a replacement formula message for a disabled formula" do allow(disabled_formula_with_replacement).to receive_messages(disable_replacement_formula: "bar", disable_replacement_cask: nil) expect(described_class.message(disabled_formula_with_replacement)) .to eq "disabled because it is broken!\nReplacement:\n brew install --formula bar\n" end it "returns a replacement cask message for a disabled formula" do allow(disabled_formula_with_replacement).to receive_messages(disable_replacement_formula: nil, disable_replacement_cask: "bar") expect(described_class.message(disabled_formula_with_replacement)) .to eq "disabled because it is broken!\nReplacement:\n brew install --cask bar\n" end it "returns a replacement formula message for a deprecated cask" do allow(deprecated_cask_with_replacement).to receive_messages(deprecation_replacement_formula: "baz", deprecation_replacement_cask: nil) expect(described_class.message(deprecated_cask_with_replacement)) .to eq "deprecated because it is discontinued upstream!\nReplacement:\n brew install --formula baz\n" end it "returns a replacement cask message for a deprecated cask" do allow(deprecated_cask_with_replacement).to receive_messages(deprecation_replacement_formula: nil, deprecation_replacement_cask: "baz") expect(described_class.message(deprecated_cask_with_replacement)) .to eq "deprecated because it is discontinued upstream!\nReplacement:\n brew install --cask baz\n" end it "returns a replacement formula message for a disabled cask" do allow(disabled_cask_with_replacement).to receive_messages(disable_replacement_formula: "qux", disable_replacement_cask: nil) expect(described_class.message(disabled_cask_with_replacement)) .to eq "disabled!\nReplacement:\n brew install --formula qux\n" end it "returns a replacement cask message for a disabled cask" do allow(disabled_cask_with_replacement).to receive_messages(disable_replacement_formula: nil, disable_replacement_cask: "qux") expect(described_class.message(disabled_cask_with_replacement)) .to eq "disabled!\nReplacement:\n brew install --cask qux\n" end end describe "::to_reason_string_or_symbol" do it "returns the original string if it isn't a formula preset reason" do expect(described_class.to_reason_string_or_symbol("discontinued", type: :formula)).to eq "discontinued" end it "returns the original string if it isn't a cask preset reason" do expect(described_class.to_reason_string_or_symbol("does_not_build", type: :cask)).to eq "does_not_build" end it "returns a symbol if the original string is a formula preset reason" do expect(described_class.to_reason_string_or_symbol("does_not_build", type: :formula)) .to eq :does_not_build end it "returns a symbol if the original string is a cask preset reason" do expect(described_class.to_reason_string_or_symbol("discontinued", type: :cask)) .to eq :discontinued end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/requirements_spec.rb
Library/Homebrew/test/requirements_spec.rb
# frozen_string_literal: true require "requirements" RSpec.describe Requirements do subject(:requirements) { described_class.new } describe "#<<" do it "returns itself" do expect(requirements << Object.new).to be(requirements) end it "merges duplicate requirements" do klass = Class.new(Requirement) requirements << klass.new << klass.new expect(requirements.count).to eq(1) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/dependency_spec.rb
Library/Homebrew/test/dependency_spec.rb
# frozen_string_literal: true require "dependency" RSpec.describe Dependency do alias_matcher :be_a_build_dependency, :be_build describe "::new" do it "accepts a single tag" do dep = described_class.new("foo", %w[bar]) expect(dep.tags).to eq(%w[bar]) end it "accepts multiple tags" do dep = described_class.new("foo", %w[bar baz]) expect(dep.tags.sort).to eq(%w[bar baz].sort) end it "preserves symbol tags" do dep = described_class.new("foo", [:build]) expect(dep.tags).to eq([:build]) end it "accepts symbol and string tags" do dep = described_class.new("foo", [:build, "bar"]) expect(dep.tags).to eq([:build, "bar"]) end it "rejects nil names" do expect { described_class.new(nil) }.to raise_error(ArgumentError) end end describe "::merge_repeats" do it "merges duplicate dependencies" do dep = described_class.new("foo", [:build]) dep2 = described_class.new("foo", ["bar"]) dep3 = described_class.new("xyz", ["abc"]) merged = described_class.merge_repeats([dep, dep2, dep3]) expect(merged.count).to eq(2) expect(merged.first).to be_a described_class foo_named_dep = merged.find { |d| d.name == "foo" } expect(foo_named_dep.tags).to eq(["bar"]) xyz_named_dep = merged.find { |d| d.name == "xyz" } expect(xyz_named_dep.tags).to eq(["abc"]) end it "merges necessity tags" do required_dep = described_class.new("foo") recommended_dep = described_class.new("foo", [:recommended]) optional_dep = described_class.new("foo", [:optional]) deps = described_class.merge_repeats([required_dep, recommended_dep]) expect(deps.count).to eq(1) expect(deps.first).to be_required expect(deps.first).not_to be_recommended expect(deps.first).not_to be_optional deps = described_class.merge_repeats([required_dep, optional_dep]) expect(deps.count).to eq(1) expect(deps.first).to be_required expect(deps.first).not_to be_recommended expect(deps.first).not_to be_optional deps = described_class.merge_repeats([recommended_dep, optional_dep]) expect(deps.count).to eq(1) expect(deps.first).not_to be_required expect(deps.first).to be_recommended expect(deps.first).not_to be_optional end it "merges temporality tags" do normal_dep = described_class.new("foo") build_dep = described_class.new("foo", [:build]) deps = described_class.merge_repeats([normal_dep, build_dep]) expect(deps.count).to eq(1) expect(deps.first).not_to be_a_build_dependency end end specify "equality" do foo1 = described_class.new("foo") foo2 = described_class.new("foo") expect(foo1).to eq(foo2) expect(foo1).to eql(foo2) bar = described_class.new("bar") expect(foo1).not_to eq(bar) expect(foo1).not_to eql(bar) foo3 = described_class.new("foo", [:build]) expect(foo1).not_to eq(foo3) expect(foo1).not_to eql(foo3) end describe "#tap" do it "returns a tap passed a fully-qualified name" do dependency = described_class.new("foo/bar/dog") expect(dependency.tap).to eq(Tap.fetch("foo", "bar")) end it "returns no tap passed a simple name" do dependency = described_class.new("dog") expect(dependency.tap).to be_nil end end specify "#option_names" do dependency = described_class.new("foo/bar/dog") expect(dependency.option_names).to eq(%w[dog]) end describe "with no_linkage tag" do it "marks dependency as no_linkage" do dep = described_class.new("foo", [:no_linkage]) expect(dep).to be_no_linkage expect(dep).to be_required expect(dep).not_to be_build expect(dep).not_to be_test end end describe "Dependency#installed? with bottle_os_version" do subject(:dependency) { described_class.new("foo") } it "accepts macOS bottle_os_version parameter" do expect { dependency.installed?(bottle_os_version: "macOS 14") }.not_to raise_error end it "accepts Ubuntu bottle_os_version parameter" do expect { dependency.installed?(bottle_os_version: "Ubuntu 22.04") }.not_to raise_error end end describe "Dependency#satisfied? with bottle_os_version" do subject(:dependency) { described_class.new("foo") } it "accepts bottle_os_version parameter" do expect { dependency.satisfied?(bottle_os_version: "macOS 14") }.not_to raise_error end it "accepts Ubuntu bottle_os_version parameter" do expect { dependency.installed?(bottle_os_version: "Ubuntu 22.04") }.not_to raise_error end end describe "UsesFromMacOSDependency#installed? with bottle_os_version" do subject(:uses_from_macos) { described_class.new("foo", bounds: { since: :sonoma }) } it "accepts macOS bottle_os_version parameter" do expect { uses_from_macos.installed?(bottle_os_version: "macOS 14") }.not_to raise_error end it "accepts Ubuntu bottle_os_version parameter" do expect { uses_from_macos.installed?(bottle_os_version: "Ubuntu 22.04") }.not_to raise_error end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/caveats_spec.rb
Library/Homebrew/test/caveats_spec.rb
# frozen_string_literal: true require "formula" require "caveats" RSpec.describe Caveats do subject(:caveats) { described_class.new(f) } let(:f) { formula { url "foo-1.0" } } specify "#f" do expect(caveats.formula).to eq(f) end describe "#empty?" do it "returns true if the Formula has no caveats" do expect(caveats).to be_empty end it "returns false if the Formula has caveats" do f = formula do url "foo-1.0" def caveats "something" end end expect(described_class.new(f)).not_to be_empty end end describe "#caveats" do context "when service block is defined" do before do allow(Utils::Service).to receive_messages(launchctl?: true, systemctl?: true) end it "gives information about service" do f = formula do url "foo-1.0" service do run [bin/"php", "test"] end end caveats = described_class.new(f).caveats expect(f.service?).to be(true) expect(caveats).to include("#{f.bin}/php test") expect(caveats).to include("background service") end it "prints warning when no service daemon is found" do f = formula do url "foo-1.0" service do run [bin/"cmd"] end end expect(Utils::Service).to receive(:launchctl?).and_return(false) expect(Utils::Service).to receive(:systemctl?).and_return(false) expect(described_class.new(f).caveats).to include("service which can only be used on macOS or systemd!") end it "prints service startup information when service.require_root is true" do f = formula do url "foo-1.0" service do run [bin/"cmd"] require_root true end end expect(Utils::Service).to receive(:running?).with(f).once.and_return(false) expect(described_class.new(f).caveats).to include("startup") end it "prints service login information" do f = formula do url "foo-1.0" service do run [bin/"cmd"] end end expect(Utils::Service).to receive(:running?).with(f).once.and_return(false) expect(described_class.new(f).caveats).to include("restart at login") end it "gives information about require_root restarting services after upgrade" do f = formula do url "foo-1.0" service do run [bin/"cmd"] require_root true end end f_obj = described_class.new(f) expect(Utils::Service).to receive(:running?).with(f).once.and_return(true) expect(f_obj.caveats).to include(" sudo brew services restart #{f.full_name}") end it "gives information about user restarting services after upgrade" do f = formula do url "foo-1.0" service do run [bin/"cmd"] end end f_obj = described_class.new(f) expect(Utils::Service).to receive(:running?).with(f).once.and_return(true) expect(f_obj.caveats).to include(" brew services restart #{f.full_name}") end it "gives information about require_root starting services after upgrade" do f = formula do url "foo-1.0" service do run [bin/"cmd"] require_root true end end f_obj = described_class.new(f) expect(Utils::Service).to receive(:running?).with(f).once.and_return(false) expect(f_obj.caveats).to include(" sudo brew services start #{f.full_name}") end it "gives information about user starting services after upgrade" do f = formula do url "foo-1.0" service do run [bin/"cmd"] end end f_obj = described_class.new(f) expect(Utils::Service).to receive(:running?).with(f).once.and_return(false) expect(f_obj.caveats).to include(" brew services start #{f.full_name}") end it "gives information about service manual command" do f = formula do url "foo-1.0" service do run [bin/"cmd", "start"] environment_variables VAR: "foo" end end cmd = "#{HOMEBREW_CELLAR}/formula_name/1.0/bin/cmd" caveats = described_class.new(f).caveats expect(caveats).to include("if you don't want/need a background service") expect(caveats).to include("VAR=\"foo\" #{cmd} start") end it "prints info when there are custom service files" do f = formula do url "foo-1.0" service do name macos: "custom.mxcl.foo", linux: "custom.foo" end end expect(Utils::Service).to receive(:installed?).with(f).once.and_return(true) expect(Utils::Service).to receive(:running?).with(f).once.and_return(false) expect(described_class.new(f).caveats).to include("restart at login") end end context "when f.keg_only is not nil" do let(:f) do formula do url "foo-1.0" keg_only "some reason" end end let(:caveats) { described_class.new(f).caveats } it "tells formula is keg_only" do expect(caveats).to include("keg-only") end it "gives command to be run when f.bin is a directory" do Pathname.new(f.bin).mkpath expect(caveats).to include(f.opt_bin.to_s) end it "gives command to be run when f.sbin is a directory" do Pathname.new(f.sbin).mkpath expect(caveats).to include(f.opt_sbin.to_s) end context "when f.lib or f.include is a directory" do it "gives command to be run when f.lib is a directory" do Pathname.new(f.lib).mkpath expect(caveats).to include("-L#{f.opt_lib}") end it "gives command to be run when f.include is a directory" do Pathname.new(f.include).mkpath expect(caveats).to include("-I#{f.opt_include}") end it "gives PKG_CONFIG_PATH when f.lib/'pkgconfig' and f.share/'pkgconfig' are directories" do allow_any_instance_of(Object).to receive(:which).with(any_args).and_return(Pathname.new("blah")) Pathname.new(f.share/"pkgconfig").mkpath Pathname.new(f.lib/"pkgconfig").mkpath expect(caveats).to include("#{f.opt_lib}/pkgconfig") expect(caveats).to include("#{f.opt_share}/pkgconfig") end end context "when joining different caveat types together" do let(:f) do formula do url "foo-1.0" keg_only "some reason" def caveats "something else" end service do run [bin/"cmd"] end end end let(:caveats) { described_class.new(f).caveats } it "adds the correct amount of new lines to the output" do expect(Utils::Service).to receive(:launchctl?).at_least(:once).and_return(true) expect(caveats).to include("something else") expect(caveats).to include("keg-only") expect(caveats).to include("if you don't want/need a background service") expect(caveats.count("\n")).to eq(9) end end end describe "shell completions" do let(:f) do formula do url "foo-1.0" end end let(:caveats) { described_class.new(f) } let(:path) { f.prefix.resolved_path } let(:bash_completion_dir) { path/"etc/bash_completion.d" } let(:fish_vendor_completions) { path/"share/fish/vendor_completions.d" } let(:zsh_site_functions) { path/"share/zsh/site-functions" } let(:pwsh_completion_dir) { path/"share/pwsh/completions" } before do # don't try to load/fetch gcc/glibc allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false) allow_any_instance_of(Object).to receive(:which).with(any_args).and_return(Pathname.new("shell")) allow(Utils::Shell).to receive_messages(preferred: nil, parent: nil) end it "includes where Bash completions have been installed to" do bash_completion_dir.mkpath FileUtils.touch bash_completion_dir/f.name expect(caveats.completions_and_elisp.join).to include(HOMEBREW_PREFIX/"etc/bash_completion.d") end it "includes where fish completions have been installed to" do fish_vendor_completions.mkpath FileUtils.touch fish_vendor_completions/f.name expect(caveats.completions_and_elisp.join).to include(HOMEBREW_PREFIX/"share/fish/vendor_completions.d") end it "includes where zsh completions have been installed to" do zsh_site_functions.mkpath FileUtils.touch zsh_site_functions/f.name expect(caveats.completions_and_elisp.join).to include(HOMEBREW_PREFIX/"share/zsh/site-functions") end it "includes where pwsh completions have been installed to" do pwsh_completion_dir.mkpath FileUtils.touch pwsh_completion_dir/f.name expect(caveats.completions_and_elisp.join).to include(HOMEBREW_PREFIX/"share/pwsh/completions") end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/style_spec.rb
Library/Homebrew/test/style_spec.rb
# frozen_string_literal: true require "style" RSpec.describe Homebrew::Style do around do |example| FileUtils.ln_s HOMEBREW_LIBRARY_PATH, HOMEBREW_LIBRARY/"Homebrew" FileUtils.ln_s HOMEBREW_LIBRARY_PATH.parent/".rubocop.yml", HOMEBREW_LIBRARY/".rubocop.yml" example.run ensure FileUtils.rm_f HOMEBREW_LIBRARY/"Homebrew" FileUtils.rm_f HOMEBREW_LIBRARY/".rubocop.yml" end before do allow(Homebrew).to receive(:install_bundler_gems!) end describe ".check_style_json" do let(:dir) { mktmpdir } it "returns offenses when RuboCop reports offenses" do formula = dir/"my-formula.rb" formula.write <<~EOS class MyFormula < Formula end EOS style_offenses = described_class.check_style_json([formula]) expect(style_offenses.for_path(formula.realpath).map(&:message)) .to include("Extra empty line detected at class body beginning.") end end describe ".check_style_and_print" do let(:dir) { mktmpdir } it "returns true (success) for conforming file with only audit-level violations" do # This file is known to use non-rocket hashes and other things that trigger audit, # but not regular, cop violations target_file = HOMEBREW_LIBRARY_PATH/"utils.rb" style_result = described_class.check_style_and_print([target_file]) expect(style_result).to be true end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/installed_dependents_spec.rb
Library/Homebrew/test/installed_dependents_spec.rb
# frozen_string_literal: true require "installed_dependents" RSpec.describe InstalledDependents do include FileUtils def stub_formula(name, version = "1.0", &block) f = formula(name) do url "#{name}-#{version}" instance_eval(&block) if block end stub_formula_loader f stub_formula_loader f, "homebrew/core/#{f}" f end def setup_test_keg(name, version, &block) stub_formula("gcc") stub_formula("glibc") stub_formula(name, version, &block) path = HOMEBREW_CELLAR/name/version (path/"bin").mkpath %w[hiworld helloworld goodbye_cruel_world].each do |file| touch path/"bin"/file end Keg.new(path) end let!(:keg) { setup_test_keg("foo", "1.0") } let!(:keg_only_keg) do setup_test_keg("foo-keg-only", "1.0") do keg_only "a good reason" end end describe "::find_some_installed_dependents" do def setup_test_keg(name, version, &block) keg = super Tab.create(keg.to_formula, DevelopmentTools.default_compiler, :libcxx).write keg end before do keg.link keg_only_keg.optlink end def alter_tab(keg) tab = keg.tab yield tab tab.write end # 1.1.6 is the earliest version of Homebrew that generates correct runtime # dependency lists in {Tab}s. def tab_dependencies(keg, deps, homebrew_version: "1.1.6") alter_tab(keg) do |tab| tab.homebrew_version = homebrew_version tab.tabfile = keg/AbstractTab::FILENAME tab.runtime_dependencies = deps end end def unreliable_tab_dependencies(keg, deps) # 1.1.5 is (hopefully!) the last version of Homebrew that generates # incorrect runtime dependency lists in {Tab}s. tab_dependencies(keg, deps, homebrew_version: "1.1.5") end specify "a dependency with no Tap in Tab" do tap_dep = setup_test_keg("baz", "1.0") dependent = setup_test_keg("bar", "1.0") do depends_on "foo" depends_on "baz" end # allow tap_dep to be linked too FileUtils.rm_r tap_dep/"bin" tap_dep.link alter_tab(keg) { |t| t.source["tap"] = nil } tab_dependencies dependent, nil result = described_class.find_some_installed_dependents([keg, tap_dep]) expect(result).to eq([[keg, tap_dep], ["bar"]]) end specify "no dependencies anywhere" do dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, nil expect(described_class.find_some_installed_dependents([keg])).to be_nil end specify "missing Formula dependency" do dependent = setup_test_keg("bar", "1.0") do depends_on "foo" end tab_dependencies dependent, nil expect(described_class.find_some_installed_dependents([keg])).to eq([[keg], ["bar"]]) end specify "uninstalling dependent and dependency" do dependent = setup_test_keg("bar", "1.0") do depends_on "foo" end tab_dependencies dependent, nil expect(described_class.find_some_installed_dependents([keg, dependent])).to be_nil end specify "renamed dependency" do dependent = setup_test_keg("bar", "1.0") do depends_on "foo" end tab_dependencies dependent, nil stub_formula_loader Formula["foo"], "homebrew/core/foo-old" renamed_path = HOMEBREW_CELLAR/"foo-old" (HOMEBREW_CELLAR/"foo").rename(renamed_path) renamed_keg = Keg.new(renamed_path/keg.version.to_s) result = described_class.find_some_installed_dependents([renamed_keg]) expect(result).to eq([[renamed_keg], ["bar"]]) end specify "empty dependencies in Tab" do dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, [] expect(described_class.find_some_installed_dependents([keg])).to be_nil end specify "same name but different version in Tab" do dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, [{ "full_name" => keg.name, "version" => "1.1" }] expect(described_class.find_some_installed_dependents([keg])).to eq([[keg], ["bar"]]) end specify "different name and same version in Tab" do stub_formula("baz") dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, [{ "full_name" => "baz", "version" => keg.version.to_s }] expect(described_class.find_some_installed_dependents([keg])).to be_nil end specify "same name and version in Tab" do dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, [{ "full_name" => keg.name, "version" => keg.version.to_s }] expect(described_class.find_some_installed_dependents([keg])).to eq([[keg], ["bar"]]) end specify "fallback for old versions" do dependent = setup_test_keg("bar", "1.0") do depends_on "foo" end unreliable_tab_dependencies dependent, [{ "full_name" => "baz", "version" => "1.0" }] expect(described_class.find_some_installed_dependents([keg])).to eq([[keg], ["bar"]]) end specify "non-opt-linked" do keg.remove_opt_record dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, [{ "full_name" => keg.name, "version" => keg.version.to_s }] expect(described_class.find_some_installed_dependents([keg])).to be_nil end specify "keg-only" do dependent = setup_test_keg("bar", "1.0") tab_dependencies dependent, [{ "full_name" => keg_only_keg.name, "version" => "1.1" }] # different version expect(described_class.find_some_installed_dependents([keg_only_keg])).to eq([[keg_only_keg], ["bar"]]) end def stub_cask_name(name, version, dependency) c = Cask::CaskLoader.load(<<-RUBY) cask "#{name}" do version "#{version}" url "c-1" depends_on formula: "#{dependency}" end RUBY stub_cask_loader c c end def setup_test_cask(name, version, dependency) c = stub_cask_name(name, version, dependency) Cask::Caskroom.path.join(name, c.version).mkpath c end specify "identify dependent casks" do setup_test_cask("qux", "1.0.0", "foo") dependents = described_class.find_some_installed_dependents([keg]).last expect(dependents.include?("qux")).to be(true) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/api_spec.rb
Library/Homebrew/test/api_spec.rb
# frozen_string_literal: true require "api" RSpec.describe Homebrew::API do let(:text) { "foo" } let(:json) { '{"foo":"bar"}' } let(:json_hash) { JSON.parse(json) } let(:json_invalid) { '{"foo":"bar"' } def mock_curl_output(stdout: "", success: true) curl_output = instance_double(SystemCommand::Result, stdout:, success?: success) allow(Utils::Curl).to receive(:curl_output).and_return curl_output end def mock_curl_download(stdout:) allow(Utils::Curl).to receive(:curl_download) do |*_args, **kwargs| kwargs[:to].write stdout end end describe "::fetch" do it "fetches a JSON file" do mock_curl_output stdout: json fetched_json = described_class.fetch("foo.json") expect(fetched_json).to eq json_hash end it "raises an error if the file does not exist" do mock_curl_output success: false expect { described_class.fetch("bar.txt") }.to raise_error(ArgumentError, /No file found/) end it "raises an error if the JSON file is invalid" do mock_curl_output stdout: text expect { described_class.fetch("baz.txt") }.to raise_error(ArgumentError, /Invalid JSON file/) end end describe "::fetch_json_api_file" do let!(:cache_dir) { mktmpdir } before do (cache_dir/"bar.json").write "tmp" end it "fetches a JSON file" do mock_curl_download stdout: json fetched_json, = described_class.fetch_json_api_file("foo.json", target: cache_dir/"foo.json") expect(fetched_json).to eq json_hash end it "updates an existing JSON file" do mock_curl_download stdout: json fetched_json, = described_class.fetch_json_api_file("bar.json", target: cache_dir/"bar.json") expect(fetched_json).to eq json_hash end it "raises an error if the JSON file is invalid" do mock_curl_download stdout: json_invalid expect do described_class.fetch_json_api_file("baz.json", target: cache_dir/"baz.json") end.to raise_error(SystemExit) end end describe "::tap_from_source_download" do let(:api_cache_root) { Homebrew::API::HOMEBREW_CACHE_API_SOURCE } let(:cache_path) do api_cache_root/"Homebrew"/"homebrew-core"/"cf5c386c1fa2cb54279d78c0990dd7a0fa4bc327"/"Formula"/"foo.rb" end context "when given a path inside the API source cache" do it "returns the corresponding tap" do expect(described_class.tap_from_source_download(cache_path)).to eq CoreTap.instance end end context "when given a path that is not inside the API source cache" do let(:api_cache_root) { mktmpdir } it "returns nil" do expect(described_class.tap_from_source_download(cache_path)).to be_nil end end context "when given a relative path that is not inside the API source cache" do it "returns nil" do expect(described_class.tap_from_source_download(Pathname("../foo.rb"))).to be_nil end end end describe "::merge_variations" do let(:arm64_sequoia_tag) { Utils::Bottles::Tag.new(system: :sequoia, arch: :arm) } let(:sonoma_tag) { Utils::Bottles::Tag.new(system: :sonoma, arch: :intel) } let(:x86_64_linux_tag) { Utils::Bottles::Tag.new(system: :linux, arch: :intel) } let(:json) do { "name" => "foo", "foo" => "bar", "baz" => ["test1", "test2"], "variations" => { "arm64_sequoia" => { "foo" => "new" }, :sonoma => { "baz" => ["new1", "new2", "new3"] }, }, } end let(:arm64_sequoia_result) do { "name" => "foo", "foo" => "new", "baz" => ["test1", "test2"], } end let(:sonoma_result) do { "name" => "foo", "foo" => "bar", "baz" => ["new1", "new2", "new3"], } end it "returns the original JSON if no variations are found" do result = described_class.merge_variations(arm64_sequoia_result, bottle_tag: arm64_sequoia_tag) expect(result).to eq arm64_sequoia_result end it "returns the original JSON if no variations are found for the current system" do result = described_class.merge_variations(arm64_sequoia_result) expect(result).to eq arm64_sequoia_result end it "returns the original JSON without the variations if no matching variation is found" do result = described_class.merge_variations(json, bottle_tag: x86_64_linux_tag) expect(result).to eq json.except("variations") end it "returns the original JSON without the variations if no matching variation is found for the current system" do Homebrew::SimulateSystem.with(os: :linux, arch: :intel) do result = described_class.merge_variations(json) expect(result).to eq json.except("variations") end end it "returns the JSON with the matching variation applied from a string key" do result = described_class.merge_variations(json, bottle_tag: arm64_sequoia_tag) expect(result).to eq arm64_sequoia_result end it "returns the JSON with the matching variation applied from a string key for the current system" do Homebrew::SimulateSystem.with(os: :sequoia, arch: :arm) do result = described_class.merge_variations(json) expect(result).to eq arm64_sequoia_result end end it "returns the JSON with the matching variation applied from a symbol key" do result = described_class.merge_variations(json, bottle_tag: sonoma_tag) expect(result).to eq sonoma_result end it "returns the JSON with the matching variation applied from a symbol key for the current system" do Homebrew::SimulateSystem.with(os: :sonoma, arch: :intel) do result = described_class.merge_variations(json) expect(result).to eq sonoma_result end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/build_options_spec.rb
Library/Homebrew/test/build_options_spec.rb
# frozen_string_literal: true require "build_options" require "options" RSpec.describe BuildOptions do alias_matcher :be_built_with, :be_with alias_matcher :be_built_without, :be_without subject(:build_options) { described_class.new(args, opts) } let(:bad_build) { described_class.new(bad_args, opts) } let(:args) { Options.create(%w[--with-foo --with-bar --without-qux]) } let(:opts) { Options.create(%w[--with-foo --with-bar --without-baz --without-qux]) } let(:bad_args) { Options.create(%w[--with-foo --with-bar --without-bas --without-qux --without-abc]) } specify "#with?" do expect(build_options).to be_built_with("foo") expect(build_options).to be_built_with("bar") expect(build_options).to be_built_with("baz") end specify "#without?" do # rubocop:todo RSpec/AggregateExamples expect(build_options).to be_built_without("qux") expect(build_options).to be_built_without("xyz") end specify "#used_options" do # rubocop:todo RSpec/AggregateExamples expect(build_options.used_options).to include("--with-foo") expect(build_options.used_options).to include("--with-bar") end specify "#unused_options" do # rubocop:todo RSpec/AggregateExamples expect(build_options.unused_options).to include("--without-baz") end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/exceptions_spec.rb
Library/Homebrew/test/exceptions_spec.rb
# frozen_string_literal: true require "exceptions" RSpec.describe "Exception" do describe MultipleVersionsInstalledError do subject(:error) do described_class.new <<~EOS foo has multiple installed versions Run `brew uninstall --force foo` to remove all versions. EOS end it(:to_s) do expect(error.to_s).to eq <<~EOS foo has multiple installed versions Run `brew uninstall --force foo` to remove all versions. EOS end end describe NoSuchKegError do context "without a tap" do subject(:error) { described_class.new("foo") } it(:to_s) { expect(error.to_s).to eq("No such keg: #{HOMEBREW_CELLAR}/foo") } end context "with a tap" do subject(:error) { described_class.new("foo", tap:) } let(:tap) { instance_double(Tap, to_s: "u/r") } it(:to_s) { expect(error.to_s).to eq("No such keg: #{HOMEBREW_CELLAR}/foo from tap u/r") } end end describe FormulaValidationError do subject(:error) { described_class.new("foo", "sha257", "magic") } it(:to_s) do expect(error.to_s).to eq(%q(invalid attribute for formula 'foo': sha257 ("magic"))) end end describe TapFormulaOrCaskUnavailableError do subject(:error) { described_class.new(tap, "foo") } let(:tap) { instance_double(Tap, user: "u", repository: "r", to_s: "u/r", installed?: false) } it(:to_s) { expect(error.to_s).to match(%r{Please tap it and then try again: brew tap u/r}) } end describe FormulaUnavailableError do subject(:error) { described_class.new("foo") } describe "#dependent_s" do it "returns nil if there is no dependent" do expect(error.dependent_s).to be_nil end it "returns nil if it depended on by itself" do error.dependent = "foo" expect(error.dependent_s).to be_nil end it "returns a string if there is a dependent" do error.dependent = "foobar" expect(error.dependent_s).to eq(" (dependency of foobar)") end end context "without a dependent" do it(:to_s) { expect(error.to_s).to match(/^No available formula with the name "foo"\./) } end context "with a dependent" do before do error.dependent = "foobar" end it(:to_s) do expect(error.to_s).to match(/^No available formula with the name "foo" \(dependency of foobar\)\./) end end end describe TapFormulaUnavailableError do subject(:error) { described_class.new(tap, "foo") } let(:tap) { instance_double(Tap, user: "u", repository: "r", to_s: "u/r", installed?: false) } it(:to_s) { expect(error.to_s).to match(%r{Please tap it and then try again: brew tap u/r}) } end describe FormulaClassUnavailableError do subject(:error) { described_class.new("foo", "foo.rb", "Foo", list) } let(:mod) do Module.new do # These are defined within an anonymous module to avoid polluting the global namespace. # rubocop:disable RSpec/LeakyConstantDeclaration,Lint/ConstantDefinitionInBlock class Bar < Requirement; end class Baz < Formula; end # rubocop:enable RSpec/LeakyConstantDeclaration,Lint/ConstantDefinitionInBlock end end context "when there are no classes" do let(:list) { [] } it(:to_s) do expect(error.to_s).to match(/Expected to find class Foo, but found no classes\./) end end context "when the class is not derived from Formula" do let(:list) { [mod.const_get(:Bar)] } it(:to_s) do expect(error.to_s).to match(/Expected to find class Foo, but only found: Bar \(not derived from Formula!\)\./) end end context "when the class is derived from Formula" do let(:list) { [mod.const_get(:Baz)] } it(:to_s) { expect(error.to_s).to match(/Expected to find class Foo, but only found: Baz\./) } end end describe FormulaUnreadableError do subject(:error) { described_class.new("foo", formula_error) } let(:formula_error) { LoadError.new("bar") } it(:to_s) { expect(error.to_s).to eq("foo: bar") } end describe TapUnavailableError do subject(:error) { described_class.new("foo") } it(:to_s) { expect(error.to_s).to eq("No available tap foo.\nRun brew tap-new foo to create a new foo tap!\n") } end describe TapAlreadyTappedError do subject(:error) { described_class.new("foo") } it(:to_s) { expect(error.to_s).to eq("Tap foo already tapped.\n") } end describe BuildError do subject(:error) { described_class.new(formula, "badprg", ["arg1", 2, Pathname.new("arg3"), :arg4], {}) } let(:formula) { instance_double(Formula, name: "foo") } it(:to_s) { expect(error.to_s).to eq("Failed executing: badprg arg1 2 arg3 arg4") } end describe OperationInProgressError do subject(:error) { described_class.new(Pathname("foo")) } it(:to_s) { expect(error.to_s).to match(/has already locked foo/) } end describe FormulaInstallationAlreadyAttemptedError do subject(:error) { described_class.new(formula) } let(:formula) { instance_double(Formula, full_name: "foo/bar") } it(:to_s) { expect(error.to_s).to eq("Formula installation already attempted: foo/bar") } end describe FormulaConflictError do subject(:error) { described_class.new(formula, [conflict]) } let(:formula) { instance_double(Formula, full_name: "foo/qux") } let(:conflict) { instance_double(Formula::FormulaConflict, name: "bar", reason: "I decided to") } it(:to_s) { expect(error.to_s).to match(/Please `brew unlink bar` before continuing\./) } end describe CompilerSelectionError do subject(:error) { described_class.new(formula) } let(:formula) { instance_double(Formula, full_name: "foo") } it(:to_s) { expect(error.to_s).to match(/foo cannot be built with any available compilers\./) } end describe CurlDownloadStrategyError do context "when the file does not exist" do subject(:error) { described_class.new("file:///tmp/foo") } it(:to_s) { expect(error.to_s).to eq("File does not exist: /tmp/foo") } end context "when the download failed" do subject(:error) { described_class.new("https://brew.sh") } it(:to_s) { expect(error.to_s).to eq("Download failed: https://brew.sh") } end end describe ErrorDuringExecution do subject(:error) { described_class.new(["badprg", "arg1", "arg2"], status:) } let(:status) { instance_double(Process::Status, exitstatus: 17, termsig: nil) } it(:to_s) { expect(error.to_s).to eq("Failure while executing; `badprg arg1 arg2` exited with 17.") } end describe ChecksumMismatchError do subject(:error) { described_class.new("/file.tar.gz", expected_checksum, actual_checksum) } let(:expected_checksum) { instance_double(Checksum, to_s: "deadbeef") } let(:actual_checksum) { instance_double(Checksum, to_s: "deadcafe") } it(:to_s) { expect(error.to_s).to match(/SHA-256 mismatch/) } end describe ResourceMissingError do subject(:error) { described_class.new(formula, resource) } let(:formula) { instance_double(Formula, full_name: "bar") } let(:resource) { instance_double(Resource, inspect: "<resource foo>") } it(:to_s) { expect(error.to_s).to eq("bar does not define resource <resource foo>") } end describe DuplicateResourceError do subject(:error) { described_class.new(resource) } let(:resource) { instance_double(Resource, inspect: "<resource foo>") } it(:to_s) { expect(error.to_s).to eq("Resource <resource foo> is defined more than once") } end describe BottleFormulaUnavailableError do subject(:error) { described_class.new("/foo.bottle.tar.gz", "foo/1.0/.brew/foo.rb") } let(:formula) { instance_double(Formula, full_name: "foo") } it(:to_s) { expect(error.to_s).to match(/This bottle does not contain the formula file/) } end describe BuildFlagsError do subject(:error) { described_class.new(["-s"]) } it(:to_s) { expect(error.to_s).to match(/flag:\s+-s\nrequires building tools/) } end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/mcp_server_spec.rb
Library/Homebrew/test/mcp_server_spec.rb
# frozen_string_literal: true require "mcp_server" require "stringio" require "timeout" RSpec.describe Homebrew::McpServer do let(:stdin) { StringIO.new } let(:stdout) { StringIO.new } let(:stderr) { StringIO.new } let(:server) { described_class.new(stdin:, stdout:, stderr:) } let(:jsonrpc) { Homebrew::McpServer::JSON_RPC_VERSION } let(:id) { Random.rand(1000) } let(:code) { Homebrew::McpServer::ERROR_CODE } describe "#initialize" do it "sets debug_logging to false by default" do expect(server.debug_logging?).to be(false) end it "sets debug_logging to true if --debug is in ARGV" do stub_const("ARGV", ["--debug"]) expect(server.debug_logging?).to be(true) end it "sets debug_logging to true if -d is in ARGV" do stub_const("ARGV", ["-d"]) expect(server.debug_logging?).to be(true) end end describe "#debug and #log" do it "logs debug output when debug_logging is true" do stub_const("ARGV", ["--debug"]) server.debug("foo") expect(stderr.string).to include("foo") end it "does not log debug output when debug_logging is false" do server.debug("foo") expect(stderr.string).to eq("") end it "logs to stderr" do server.log("bar") expect(stderr.string).to include("bar") end end describe "#handle_request" do it "responds to initialize method" do request = { "id" => id, "method" => "initialize" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, result: { protocolVersion: Homebrew::McpServer::MCP_PROTOCOL_VERSION, capabilities: { tools: { listChanged: false }, prompts: {}, resources: {}, logging: {}, roots: {}, }, serverInfo: Homebrew::McpServer::SERVER_INFO, }, }) end it "responds to resources/list" do request = { "id" => id, "method" => "resources/list" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, result: { resources: [] } }) end it "responds to resources/templates/list" do request = { "id" => id, "method" => "resources/templates/list" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, result: { resourceTemplates: [] } }) end it "responds to prompts/list" do request = { "id" => id, "method" => "prompts/list" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, result: { prompts: [] } }) end it "responds to ping" do request = { "id" => id, "method" => "ping" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, result: {} }) end it "responds to get_server_info" do request = { "id" => id, "method" => "get_server_info" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, result: Homebrew::McpServer::SERVER_INFO }) end it "responds to logging/setLevel with debug" do request = { "id" => id, "method" => "logging/setLevel", "params" => { "level" => "debug" } } result = server.handle_request(request) expect(server.debug_logging?).to be(true) expect(result).to eq({ jsonrpc:, id:, result: {} }) end it "responds to logging/setLevel with non-debug" do request = { "id" => id, "method" => "logging/setLevel", "params" => { "level" => "info" } } result = server.handle_request(request) expect(server.debug_logging?).to be(false) expect(result).to eq({ jsonrpc:, id:, result: {} }) end it "responds to notifications/initialized" do request = { "id" => id, "method" => "notifications/initialized" } expect(server.handle_request(request)).to be_nil end it "responds to notifications/cancelled" do request = { "id" => id, "method" => "notifications/cancelled" } expect(server.handle_request(request)).to be_nil end it "responds to tools/list" do request = { "id" => id, "method" => "tools/list" } result = server.handle_request(request) expect(result[:result][:tools]).to match_array(Homebrew::McpServer::TOOLS.values) end Homebrew::McpServer::TOOLS.each do |tool_name, tool_definition| it "responds to tools/call for #{tool_name}" do allow(Open3).to receive(:popen2e).and_return("output for #{tool_name}") arguments = {} Array(tool_definition[:required]).each do |required_key| arguments[required_key] = "dummy" end request = { "id" => id, "method" => "tools/call", "params" => { "name" => tool_name.to_s, "arguments" => arguments, }, } result = server.handle_request(request) expect(result).to eq({ jsonrpc: jsonrpc, id: id, result: { content: [{ type: "text", text: "output for #{tool_name}" }] }, }) end end it "responds to tools/call for unknown tool" do request = { "id" => id, "method" => "tools/call", "params" => { "name" => "not_a_tool", "arguments" => {} } } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, error: { message: "Unknown tool", code: } }) end it "responds with error for unknown method" do request = { "id" => id, "method" => "not_a_method" } result = server.handle_request(request) expect(result).to eq({ jsonrpc:, id:, error: { message: "Method not found", code: } }) end it "returns nil if id is nil" do request = { "method" => "initialize" } expect(server.handle_request(request)).to be_nil end end describe "#respond_result" do it "returns nil if id is nil" do expect(server.send(:respond_result, nil, {})).to be_nil end it "returns a result hash if id is present" do result = server.respond_result(id, { foo: "bar" }) expect(result).to eq({ jsonrpc:, id:, result: { foo: "bar" } }) end end describe "#respond_error" do it "returns an error hash" do result = server.respond_error(id, "fail") expect(result).to eq({ jsonrpc:, id:, error: { message: "fail", code: } }) end end describe "#run" do let(:sleep_time) { 0.001 } it "runs the loop and exits cleanly on interrupt" do stub_const("ARGV", ["--debug"]) stdin.puts({ id:, method: "ping" }.to_json) stdin.rewind server_thread = Thread.new do server.run rescue SystemExit # expected, do nothing end response_hash_string = "Response: {" sleep(sleep_time) server_thread.raise(Interrupt) server_thread.join expect(stderr.string).to include(response_hash_string) end it "runs the loop and logs 'Response: nil' when handle_request returns nil" do stub_const("ARGV", ["--debug"]) stdin.puts({ id:, method: "notifications/initialized" }.to_json) stdin.rewind server_thread = Thread.new do server.run rescue SystemExit # expected, do nothing end response_nil_string = "Response: nil" sleep(sleep_time) server_thread.raise(Interrupt) server_thread.join expect(stderr.string).to include(response_nil_string) end it "exits on Interrupt" do stdin.puts stdin.rewind allow(stdin).to receive(:gets).and_raise(Interrupt) expect do server.run rescue SystemExit end.to raise_error(SystemExit) end it "exits on error" do stdin.puts stdin.rewind allow(stdin).to receive(:gets).and_raise(StandardError, "fail") expect do server.run rescue SystemExit end.to raise_error(SystemExit) expect(stderr.string).to match(/Error: fail/) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/livecheck_spec.rb
Library/Homebrew/test/livecheck_spec.rb
# frozen_string_literal: true require "formula" require "livecheck" RSpec.describe Livecheck do let(:f) do formula do homepage "https://brew.sh" url "https://brew.sh/test-0.0.1.tgz" head "https://github.com/Homebrew/brew.git", branch: "main" end end let(:livecheck_f) { described_class.new(f.class) } let(:c) do Cask::CaskLoader.load(+<<-RUBY) cask "test" do version "0.0.1,2" url "https://brew.sh/test-0.0.1.dmg" name "Test" desc "Test cask" homepage "https://brew.sh" end RUBY end let(:livecheck_c) { described_class.new(c) } let(:post_hash) do { empty: "", boolean: "true", number: "1", string: "a + b = c", } end describe "#formula" do it "returns nil if not set" do expect(livecheck_f.formula).to be_nil end it "returns the String if set" do livecheck_f.formula("other-formula") expect(livecheck_f.formula).to eq("other-formula") end it "raises a TypeError if the argument isn't a String" do expect do livecheck_f.formula(123) end.to raise_error TypeError end end describe "#cask" do it "returns nil if not set" do expect(livecheck_c.cask).to be_nil end it "returns the String if set" do livecheck_c.cask("other-cask") expect(livecheck_c.cask).to eq("other-cask") end end describe "#regex" do it "returns nil if not set" do expect(livecheck_f.regex).to be_nil end it "returns the Regexp if set" do livecheck_f.regex(/foo/) expect(livecheck_f.regex).to eq(/foo/) end end describe "#skip" do it "sets @skip to true when no argument is provided" do expect(livecheck_f.skip).to be true expect(livecheck_f.instance_variable_get(:@skip)).to be true expect(livecheck_f.instance_variable_get(:@skip_msg)).to be_nil end it "sets @skip to true and @skip_msg to the provided String" do expect(livecheck_f.skip("foo")).to be true expect(livecheck_f.instance_variable_get(:@skip)).to be true expect(livecheck_f.instance_variable_get(:@skip_msg)).to eq("foo") end end describe "#skip?" do it "returns the value of @skip" do expect(livecheck_f.skip?).to be false livecheck_f.skip expect(livecheck_f.skip?).to be true end end describe "#strategy" do let(:block) do proc { |page, regex| page.scan(regex).map { |match| match[0].tr("_", ".") } } end it "returns nil if not set" do expect(livecheck_f.strategy).to be_nil expect(livecheck_f.strategy_block).to be_nil end it "returns the Symbol if set" do livecheck_f.strategy(:page_match) expect(livecheck_f.strategy).to eq(:page_match) expect(livecheck_f.strategy_block).to be_nil end it "sets `strategy_block` when provided" do livecheck_f.strategy(:page_match, &block) expect(livecheck_f.strategy).to eq(:page_match) expect(livecheck_f.strategy_block).to eq(block) end end describe "#throttle" do it "returns nil if not set" do expect(livecheck_f.throttle).to be_nil end it "returns the Integer if set" do livecheck_f.throttle(10) expect(livecheck_f.throttle).to eq(10) end end describe "#url" do let(:url_string) { "https://brew.sh" } let(:referer_url) { "https://example.com/referer" } it "returns nil if not set" do expect(livecheck_f.url).to be_nil end it "returns a string when set to a string" do livecheck_f.url(url_string) expect(livecheck_f.url).to eq(url_string) end it "returns the URL symbol if valid" do livecheck_f.url(:head) expect(livecheck_f.url).to eq(:head) livecheck_f.url(:homepage) expect(livecheck_f.url).to eq(:homepage) livecheck_f.url(:stable) expect(livecheck_f.url).to eq(:stable) livecheck_c.url(:url) expect(livecheck_c.url).to eq(:url) end it "sets `url` options when provided" do # This test makes sure that we can set multiple options at once and # options from subsequent `url` calls are merged with existing values # (i.e. existing values aren't reset to `nil`). [We only call `url` once # in a `livecheck` block but this should technically work due to how it's # implemented.] livecheck_f.url( url_string, cookies: { "cookie_key" => "cookie_value" }, header: "Accept: */*", homebrew_curl: true, post_form: post_hash, referer: referer_url, user_agent: :browser, ) livecheck_f.url(url_string, post_json: post_hash) expect(livecheck_f.options.homebrew_curl).to be(true) expect(livecheck_f.options.post_form).to eq(post_hash) expect(livecheck_f.options.post_json).to eq(post_hash) expect(livecheck_f.options.referer).to eq(referer_url) expect(livecheck_f.options.user_agent).to eq(:browser) header_array = ["Accept: */*", "X-Requested-With: XMLHttpRequest"] livecheck_f.url(url_string, header: header_array) expect(livecheck_f.options.header).to eq(header_array) livecheck_f.url(url_string, user_agent: "Example") expect(livecheck_f.options.user_agent).to eq("Example") end it "raises an ArgumentError if the argument isn't a valid Symbol" do expect do livecheck_f.url(:not_a_valid_symbol) end.to raise_error ArgumentError end it "raises an ArgumentError if both `post_form` and `post_json` arguments are provided" do expect do livecheck_f.url(:stable, post_form: post_hash, post_json: post_hash) end.to raise_error ArgumentError end end describe "#arch" do let(:c_arch) do Cask::Cask.new("c-arch") do arch arm: "arm", intel: "intel" version "0.0.1" url "https://brew.sh/test-0.0.1.dmg" name "Test" desc "Test cask" homepage "https://brew.sh" livecheck do url "https://brew.sh/#{arch}" end end end { needs_arm: "arm", needs_intel: "intel", }.each do |metadata, expected_arch| it "delegates `arch` in `livecheck` block to `package_or_resource`", metadata do expect(c_arch.livecheck.url).to eq("https://brew.sh/#{expected_arch}") end end end describe "#os" do let(:c_os) do Cask::Cask.new("c-os") do os macos: "macos", linux: "linux" version "0.0.1" url "https://brew.sh/test-0.0.1.dmg" name "Test" desc "Test cask" homepage "https://brew.sh" livecheck do url "https://brew.sh/#{os}" end end end { needs_macos: "macos", needs_linux: "linux", }.each do |metadata, expected_os| it "delegates `os` in `livecheck` block to `package_or_resource`", metadata do expect(c_os.livecheck.url).to eq("https://brew.sh/#{expected_os}") end end end describe "#version" do let(:url_with_version) { "https://brew.sh/0.0.1" } let(:f_version) do formula do homepage "https://brew.sh" url "https://brew.sh/test-0.0.1.tgz" livecheck do url "https://brew.sh/#{version}" end end end let(:c_version) do Cask::Cask.new("c-version") do version "0.0.1" url "https://brew.sh/test-0.0.1.dmg" name "Test" desc "Test cask" homepage "https://brew.sh" livecheck do url "https://brew.sh/#{version}" end end end let(:r_version) do Resource.new do url "https://brew.sh/test-0.0.1.tgz" livecheck do url "https://brew.sh/#{version}" end end end it "delegates `version` in `livecheck` block to `package_or_resource`" do expect(f_version.livecheck.url).to eq(url_with_version) expect(c_version.livecheck.url).to eq(url_with_version) expect(r_version.livecheck.url).to eq(url_with_version) end end describe "#to_hash" do it "returns a Hash of all instance variables" do expect(livecheck_f.to_hash).to eq( { "options" => Homebrew::Livecheck::Options.new.to_hash, "cask" => nil, "formula" => nil, "regex" => nil, "skip" => false, "skip_msg" => nil, "strategy" => nil, "throttle" => nil, "url" => nil, }, ) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/simulate_system_spec.rb
Library/Homebrew/test/simulate_system_spec.rb
# frozen_string_literal: true require "settings" RSpec.describe Homebrew::SimulateSystem do after do described_class.clear end describe "::simulating_or_running_on_macos?" do it "returns true on macOS", :needs_macos do described_class.clear expect(described_class.simulating_or_running_on_macos?).to be true end it "returns false on Linux", :needs_linux do described_class.clear expect(described_class.simulating_or_running_on_macos?).to be false end it "returns false on macOS when simulating Linux", :needs_macos do described_class.clear described_class.os = :linux expect(described_class.simulating_or_running_on_macos?).to be false end it "returns true on Linux when simulating a generic macOS version", :needs_linux do described_class.clear described_class.os = :macos expect(described_class.simulating_or_running_on_macos?).to be true end it "returns true on Linux when simulating a specific macOS version", :needs_linux do described_class.clear described_class.os = :monterey expect(described_class.simulating_or_running_on_macos?).to be true end it "returns true on Linux with HOMEBREW_SIMULATE_MACOS_ON_LINUX", :needs_linux do described_class.clear ENV["HOMEBREW_SIMULATE_MACOS_ON_LINUX"] = "1" expect(described_class.simulating_or_running_on_macos?).to be true end end describe "::simulating_or_running_on_linux?" do it "returns true on Linux", :needs_linux do described_class.clear expect(described_class.simulating_or_running_on_linux?).to be true end it "returns false on macOS", :needs_macos do described_class.clear expect(described_class.simulating_or_running_on_linux?).to be false end it "returns true on macOS when simulating Linux", :needs_macos do described_class.clear described_class.os = :linux expect(described_class.simulating_or_running_on_linux?).to be true end it "returns false on Linux when simulating a generic macOS version", :needs_linux do described_class.clear described_class.os = :macos expect(described_class.simulating_or_running_on_linux?).to be false end it "returns false on Linux when simulating a specific macOS version", :needs_linux do described_class.clear described_class.os = :monterey expect(described_class.simulating_or_running_on_linux?).to be false end it "returns false on Linux with HOMEBREW_SIMULATE_MACOS_ON_LINUX", :needs_linux do described_class.clear ENV["HOMEBREW_SIMULATE_MACOS_ON_LINUX"] = "1" expect(described_class.simulating_or_running_on_linux?).to be false end end describe "::current_arch" do it "returns the current architecture" do described_class.clear expect(described_class.current_arch).to eq Hardware::CPU.type end it "returns the simulated architecture" do described_class.clear simulated_arch = if Hardware::CPU.arm? :intel else :arm end described_class.arch = simulated_arch expect(described_class.current_arch).to eq simulated_arch end end describe "::current_os" do it "returns the current macOS version on macOS", :needs_macos do described_class.clear expect(described_class.current_os).to eq MacOS.version.to_sym end it "returns `:linux` on Linux", :needs_linux do described_class.clear expect(described_class.current_os).to eq :linux end it "returns `:linux` when simulating Linux on macOS", :needs_macos do described_class.clear described_class.os = :linux expect(described_class.current_os).to eq :linux end it "returns `:macos` when simulating a generic macOS version on Linux", :needs_linux do described_class.clear described_class.os = :macos expect(described_class.current_os).to eq :macos end it "returns `:macos` when simulating a specific macOS version on Linux", :needs_linux do described_class.clear described_class.os = :monterey expect(described_class.current_os).to eq :monterey end it "returns the current macOS version on macOS with HOMEBREW_SIMULATE_MACOS_ON_LINUX", :needs_macos do described_class.clear ENV["HOMEBREW_SIMULATE_MACOS_ON_LINUX"] = "1" expect(described_class.current_os).to eq MacOS.version.to_sym end it "returns `:macos` on Linux with HOMEBREW_SIMULATE_MACOS_ON_LINUX", :needs_linux do described_class.clear ENV["HOMEBREW_SIMULATE_MACOS_ON_LINUX"] = "1" expect(described_class.current_os).to eq :macos end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_auditor_spec.rb
Library/Homebrew/test/formula_auditor_spec.rb
# frozen_string_literal: true require "formula_auditor" require "git_repository" require "securerandom" RSpec.describe Homebrew::FormulaAuditor do include FileUtils include Test::Helper::Formula let(:dir) { mktmpdir } let(:foo_version) do @count ||= 0 @count += 1 end let(:formula_subpath) { "Formula/foo#{foo_version}.rb" } let(:origin_tap_path) { HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-foo" } let(:origin_formula_path) { origin_tap_path/formula_subpath } let(:tap_path) { HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-bar" } let(:formula_path) { tap_path/formula_subpath } def formula_auditor(name, text, options = {}) path = Pathname.new "#{dir}/#{name}.rb" path.open("w") do |f| f.write text end formula = Formulary.factory(path) if options.key? :tap_audit_exceptions tap = Tap.fetch("test/tap") allow(tap).to receive(:audit_exceptions).and_return(options[:tap_audit_exceptions]) allow(formula).to receive(:tap).and_return(tap) options.delete :tap_audit_exceptions end described_class.new(formula, options) end def formula_gsub(before, after = "") text = formula_path.read text.gsub! before, after formula_path.unlink formula_path.write text end def test_formula_source(name:, compatibility_version: nil, revision: 0, depends_on: []) class_name = name.gsub(/[^0-9a-z]/i, "_").split("_").reject(&:empty?).map(&:capitalize).join class_name = "TestFormula#{SecureRandom.hex(2)}" if class_name.empty? lines = [] lines << "class #{class_name} < Formula" lines << ' desc "Test formula"' lines << ' homepage "https://brew.sh"' lines << %Q( url "https://brew.sh/#{name}-1.0.tar.gz") lines << ' sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e"' lines << " compatibility_version #{compatibility_version}" if compatibility_version lines << " revision #{revision}" if revision.positive? Array(depends_on).each { |dep| lines << %Q( depends_on "#{dep}") } lines << " def install" lines << " bin.mkpath" lines << " end" lines << "end" "#{lines.join("\n")}\n" end def formula_gsub_origin_commit(before, after = "") text = origin_formula_path.read text.gsub!(before, after) origin_formula_path.unlink origin_formula_path.write text origin_tap_path.cd do system "git", "commit", "-am", "commit" end tap_path.cd do system "git", "fetch" system "git", "reset", "--hard", "origin/HEAD" end end describe "#problems" do it "is empty by default" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" end RUBY expect(fa.problems).to be_empty end end describe "#audit_license" do let(:spdx_license_data) { SPDX.license_data } let(:spdx_exception_data) { SPDX.exception_data } let(:deprecated_spdx_id) { "GPL-1.0" } let(:license_all_custom_id) { 'all_of: ["MIT", "zzz"]' } let(:deprecated_spdx_exception) { "Nokia-Qt-exception-1.1" } let(:license_any) { 'any_of: ["0BSD", "GPL-3.0-only"]' } let(:license_any_with_plus) { 'any_of: ["0BSD+", "GPL-3.0-only"]' } let(:license_nested_conditions) { 'any_of: ["0BSD", { all_of: ["GPL-3.0-only", "MIT"] }]' } let(:license_any_mismatch) { 'any_of: ["0BSD", "MIT"]' } let(:license_any_nonstandard) { 'any_of: ["0BSD", "zzz", "MIT"]' } let(:license_any_deprecated) { 'any_of: ["0BSD", "GPL-1.0", "MIT"]' } it "does not check if the formula is not a new formula" do fa = formula_auditor "foo", <<~RUBY, new_formula: false class Foo < Formula url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_license expect(fa.problems).to be_empty end it "detects no license info" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true, core_tap: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_license expect(fa.problems.first[:message]).to match "Formulae in homebrew/core must specify a license." end it "detects if license is not a standard spdx-id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license "zzz" end RUBY fa.audit_license expect(fa.problems.first[:message]).to match <<~EOS Formula foo contains non-standard SPDX licenses: ["zzz"]. For a list of valid licenses check: https://spdx.org/licenses/ EOS end it "detects if license is a deprecated spdx-id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true, strict: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license "#{deprecated_spdx_id}" end RUBY fa.audit_license expect(fa.problems.first[:message]).to eq <<~EOS Formula foo contains deprecated SPDX licenses: ["GPL-1.0"]. You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). For a list of valid licenses check: https://spdx.org/licenses/ EOS end it "detects if license with AND contains a non-standard spdx-id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license #{license_all_custom_id} end RUBY fa.audit_license expect(fa.problems.first[:message]).to match <<~EOS Formula foo contains non-standard SPDX licenses: ["zzz"]. For a list of valid licenses check: https://spdx.org/licenses/ EOS end it "detects if license array contains a non-standard spdx-id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license #{license_any_nonstandard} end RUBY fa.audit_license expect(fa.problems.first[:message]).to match <<~EOS Formula foo contains non-standard SPDX licenses: ["zzz"]. For a list of valid licenses check: https://spdx.org/licenses/ EOS end it "detects if license array contains a deprecated spdx-id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true, strict: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license #{license_any_deprecated} end RUBY fa.audit_license expect(fa.problems.first[:message]).to eq <<~EOS Formula foo contains deprecated SPDX licenses: ["GPL-1.0"]. You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). For a list of valid licenses check: https://spdx.org/licenses/ EOS end it "verifies that a license info is a standard spdx id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license "0BSD" end RUBY fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license info with plus is a standard spdx id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license "0BSD+" end RUBY fa.audit_license expect(fa.problems).to be_empty end it "allows :public_domain license" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license :public_domain end RUBY fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license info with multiple licenses are standard spdx ids" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license any_of: ["0BSD", "MIT"] end RUBY fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license info with exceptions are standard spdx ids" do formula_text = <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license "Apache-2.0" => { with: "LLVM-exception" } end RUBY fa = formula_auditor("foo", formula_text, new_formula: true, spdx_license_data:, spdx_exception_data:) fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license array contains only standard spdx id" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license #{license_any} end RUBY fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license array contains only standard spdx id with plus" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license #{license_any_with_plus} end RUBY fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license array with AND contains only standard spdx ids" do fa = formula_auditor "foo", <<~RUBY, spdx_license_data:, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" license #{license_nested_conditions} end RUBY fa.audit_license expect(fa.problems).to be_empty end it "checks online and verifies that a standard license id is the same " \ "as what is indicated on its GitHub repo", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "GPL-3.0-or-later" end RUBY fa = formula_auditor "cask", formula_text, spdx_license_data:, online: true, core_tap: true, new_formula: true fa.audit_license expect(fa.problems).to be_empty end it "checks online and verifies that a standard license id with AND is the same " \ "as what is indicated on its GitHub repo", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license all_of: ["GPL-3.0-or-later", "MIT"] end RUBY fa = formula_auditor "cask", formula_text, spdx_license_data:, online: true, core_tap: true, new_formula: true fa.audit_license expect(fa.problems).to be_empty end it "checks online and verifies that a standard license id with WITH is the same " \ "as what is indicated on its GitHub repo", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "GPL-3.0-or-later" => { with: "LLVM-exception" } end RUBY fa = formula_auditor("cask", formula_text, online: true, core_tap: true, new_formula: true, spdx_license_data:, spdx_exception_data:) fa.audit_license expect(fa.problems).to be_empty end it "verifies that a license exception has standard spdx ids", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "GPL-3.0-or-later" => { with: "zzz" } end RUBY fa = formula_auditor("cask", formula_text, core_tap: true, new_formula: true, spdx_license_data:, spdx_exception_data:) fa.audit_license expect(fa.problems.first[:message]).to match <<~EOS Formula cask contains invalid or deprecated SPDX license exceptions: ["zzz"]. For a list of valid license exceptions check: https://spdx.org/licenses/exceptions-index.html EOS end it "verifies that a license exception has non-deprecated spdx ids", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "GPL-3.0-or-later" => { with: "#{deprecated_spdx_exception}" } end RUBY fa = formula_auditor("cask", formula_text, core_tap: true, new_formula: true, spdx_license_data:, spdx_exception_data:) fa.audit_license expect(fa.problems.first[:message]).to match <<~EOS Formula cask contains invalid or deprecated SPDX license exceptions: ["#{deprecated_spdx_exception}"]. For a list of valid license exceptions check: https://spdx.org/licenses/exceptions-index.html EOS end it "checks online and verifies that a standard license id is in the same exempted license group " \ "as what is indicated on its GitHub repo", :needs_network do fa = formula_auditor "cask", <<~RUBY, spdx_license_data:, online: true, new_formula: true class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "GPL-3.0-or-later" end RUBY fa.audit_license expect(fa.problems).to be_empty end it "checks online and verifies that a standard license array is in the same exempted license group " \ "as what is indicated on its GitHub repo", :needs_network do fa = formula_auditor "cask", <<~RUBY, spdx_license_data:, online: true, new_formula: true class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license any_of: ["GPL-3.0-or-later", "MIT"] end RUBY fa.audit_license expect(fa.problems).to be_empty end it "checks online and detects that a formula-specified license is not " \ "the same as what is indicated on its GitHub repository", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "0BSD" end RUBY fa = formula_auditor "cask", formula_text, spdx_license_data:, online: true, core_tap: true, new_formula: true fa.audit_license expect(fa.problems.first[:message]) .to eq 'Formula license ["0BSD"] does not match GitHub license ["GPL-3.0"].' end it "allows a formula-specified license that differs from its GitHub " \ "repository for formulae on the mismatched license allowlist", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license "0BSD" end RUBY fa = formula_auditor "cask", formula_text, spdx_license_data:, online: true, core_tap: true, new_formula: true, tap_audit_exceptions: { permitted_formula_license_mismatches: ["cask"] } fa.audit_license expect(fa.problems).to be_empty end it "checks online and detects that an array of license does not contain " \ "what is indicated on its GitHub repository", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license #{license_any_mismatch} end RUBY fa = formula_auditor "cask", formula_text, spdx_license_data:, online: true, core_tap: true, new_formula: true fa.audit_license expect(fa.problems.first[:message]).to match "Formula license [\"0BSD\", \"MIT\"] " \ "does not match GitHub license [\"GPL-3.0\"]." end it "checks online and verifies that an array of license contains " \ "what is indicated on its GitHub repository", :needs_network do formula_text = <<~RUBY class Cask < Formula url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" head "https://github.com/cask/cask.git", branch: "main" license #{license_any} end RUBY fa = formula_auditor "cask", formula_text, spdx_license_data:, online: true, core_tap: true, new_formula: true fa.audit_license expect(fa.problems).to be_empty end end describe "#audit_file" do specify "no issue" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" end RUBY fa.audit_file expect(fa.problems).to be_empty end end describe "#audit_name" do specify "no issue" do fa = formula_auditor "foo", <<~RUBY, core_tap: true, strict: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" end RUBY fa.audit_name expect(fa.problems).to be_empty end specify "uppercase formula name" do fa = formula_auditor "Foo", <<~RUBY class Foo < Formula url "https://brew.sh/Foo-1.0.tgz" homepage "https://brew.sh" end RUBY fa.audit_name expect(fa.problems.first[:message]).to match "must not contain uppercase letters" end end describe "#audit_resource_name_matches_pypi_package_name_in_url" do it "reports a problem if the resource name does not match the python sdist name" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "abc123" homepage "https://brew.sh" resource "Something" do url "https://files.pythonhosted.org/packages/FooSomething-1.0.0.tar.gz" sha256 "def456" end end RUBY fa.audit_specs expect(fa.problems.first[:message]) .to match("`resource` name should be 'FooSomething' to match the PyPI package name") end it "reports a problem if the resource name does not match the python wheel name" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "abc123" homepage "https://brew.sh" resource "Something" do url "https://files.pythonhosted.org/packages/FooSomething-1.0.0-py3-none-any.whl" sha256 "def456" end end RUBY fa.audit_specs expect(fa.problems.first[:message]) .to match("`resource` name should be 'FooSomething' to match the PyPI package name") end end describe "#check_service_command" do specify "Not installed" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" service do run [] end end RUBY expect(fa.check_service_command(fa.formula)).to match nil end specify "No service" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" end RUBY mkdir_p fa.formula.prefix expect(fa.check_service_command(fa.formula)).to match nil end specify "No command" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" service do run [] end end RUBY mkdir_p fa.formula.prefix expect(fa.check_service_command(fa.formula)).to match nil end specify "Invalid command" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" service do run [HOMEBREW_PREFIX/"bin/something"] end end RUBY mkdir_p fa.formula.prefix expect(fa.check_service_command(fa.formula)).to match "Service command does not exist" end end describe "#audit_github_repository" do specify "#audit_github_repository when HOMEBREW_NO_GITHUB_API is set" do ENV["HOMEBREW_NO_GITHUB_API"] = "1" fa = formula_auditor "foo", <<~RUBY, strict: true, online: true class Foo < Formula homepage "https://github.com/example/example" url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_github_repository expect(fa.problems).to be_empty end end describe "#audit_github_repository_archived" do specify "#audit_github_repository_archived when HOMEBREW_NO_GITHUB_API is set" do fa = formula_auditor "foo", <<~RUBY, strict: true, online: true class Foo < Formula homepage "https://github.com/example/example" url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_github_repository_archived expect(fa.problems).to be_empty end end describe "#audit_gitlab_repository" do specify "#audit_gitlab_repository for stars, forks and creation date" do fa = formula_auditor "foo", <<~RUBY, strict: true, online: true class Foo < Formula homepage "https://gitlab.com/libtiff/libtiff" url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_gitlab_repository expect(fa.problems).to be_empty end end describe "#audit_gitlab_repository_archived" do specify "#audit gitlab repository for archived status" do fa = formula_auditor "foo", <<~RUBY, strict: true, online: true class Foo < Formula homepage "https://gitlab.com/libtiff/libtiff" url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_gitlab_repository_archived expect(fa.problems).to be_empty end end describe "#audit_bitbucket_repository" do specify "#audit_bitbucket_repository for stars, forks and creation date" do fa = formula_auditor "foo", <<~RUBY, strict: true, online: true class Foo < Formula homepage "https://bitbucket.com/libtiff/libtiff" url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_bitbucket_repository expect(fa.problems).to be_empty end end describe "#audit_specs" do let(:livecheck_throttle) { "livecheck do\n throttle 10\n end" } let(:versioned_head_spec_list) { { versioned_head_spec_allowlist: ["foo"] } } it "doesn't allow to miss a checksum" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" end RUBY fa.audit_specs expect(fa.problems.first[:message]).to match "Checksum is missing" end it "allows to miss a checksum for git strategy" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo.git", tag: "1.0", revision: "f5e00e485e7aa4c5baa20355b27e3b84a6912790" end RUBY fa.audit_specs expect(fa.problems).to be_empty end it "allows to miss a checksum for HEAD" do fa = formula_auditor "foo", <<~RUBY class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://brew.sh/foo.tgz" end RUBY fa.audit_specs expect(fa.problems).to be_empty end it "requires `branch:` to be specified for Git head URLs" do fa = formula_auditor "foo", <<~RUBY, online: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://github.com/Homebrew/homebrew-test-bot.git" end RUBY fa.audit_specs # This is `.last` because the first problem is the unreachable stable URL. expect(fa.problems.last[:message]).to match("Git `head` URL must specify a branch name") end it "suggests a detected default branch for Git head URLs" do fa = formula_auditor "foo", <<~RUBY, online: true, core_tap: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://github.com/Homebrew/homebrew-test-bot.git", branch: "master" end RUBY message = "To use a non-default HEAD branch, add the formula to `head_non_default_branch_allowlist.json`." fa.audit_specs # This is `.last` because the first problem is the unreachable stable URL. expect(fa.problems.last[:message]).to match(message) end it "can specify a default branch without an allowlist if not in a core tap" do fa = formula_auditor "foo", <<~RUBY, online: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://github.com/Homebrew/homebrew-test-bot.git", branch: "main" end RUBY fa.audit_specs expect(fa.problems).not_to match("Git `head` URL must specify a branch name") end it "ignores `branch:` for non-Git head URLs" do fa = formula_auditor "foo", <<~RUBY, online: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://brew.sh/foo.tgz", branch: "develop" end RUBY fa.audit_specs expect(fa.problems).not_to match("Git `head` URL must specify a branch name") end it "ignores `branch:` for `resource` URLs" do fa = formula_auditor "foo", <<~RUBY, online: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" resource "bar" do url "https://raw.githubusercontent.com/Homebrew/homebrew-core/HEAD/Formula/bar.rb" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" end end RUBY fa.audit_specs expect(fa.problems).not_to match("Git `head` URL must specify a branch name") end it "allows versions with no throttle rate" do fa = formula_auditor "bar", <<~RUBY, core_tap: true class Bar < Formula url "https://brew.sh/foo-1.0.1.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" end RUBY fa.audit_specs expect(fa.problems).to be_empty end it "allows major/minor versions with throttle rate" do fa = formula_auditor "foo", <<~RUBY, core_tap: true class Foo < Formula url "https://brew.sh/foo-1.0.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" #{livecheck_throttle} end RUBY fa.audit_specs expect(fa.problems).to be_empty end it "allows patch versions to be multiples of the throttle rate" do fa = formula_auditor "foo", <<~RUBY, core_tap: true class Foo < Formula url "https://brew.sh/foo-1.0.10.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" #{livecheck_throttle} end RUBY fa.audit_specs expect(fa.problems).to be_empty end it "doesn't allow patch versions that aren't multiples of the throttle rate" do fa = formula_auditor "foo", <<~RUBY, core_tap: true class Foo < Formula url "https://brew.sh/foo-1.0.1.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" #{livecheck_throttle} end RUBY fa.audit_specs expect(fa.problems.first[:message]).to match "Should only be updated every 10 releases on multiples of 10" end it "allows non-versioned formulae to have a `HEAD` spec" do fa = formula_auditor "bar", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list class Bar < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://brew.sh/foo.git", branch: "develop" end RUBY fa.audit_specs expect(fa.problems).to be_empty end it "doesn't allow versioned formulae to have a `HEAD` spec" do fa = formula_auditor "bar@1", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list class BarAT1 < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://brew.sh/foo.git", branch: "develop" end RUBY fa.audit_specs expect(fa.problems.first[:message]).to match "Versioned formulae should not have a `head` spec" end it "allows versioned formulae on the allowlist to have a `HEAD` spec" do fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list class Foo < Formula url "https://brew.sh/foo-1.0.tgz" sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" head "https://brew.sh/foo.git", branch: "develop" end RUBY fa.audit_specs expect(fa.problems).to be_empty end end describe "#audit_deps" do describe "a dependency on a macOS-provided keg-only formula" do describe "which is allowlisted" do subject(:f_a) { fa } let(:fa) do formula_auditor "foo", <<~RUBY, new_formula: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" depends_on "openssl" end RUBY end let(:f_openssl) do formula do url "https://brew.sh/openssl-1.0.tgz" homepage "https://brew.sh" keg_only :provided_by_macos end end before do allow(fa.formula.deps.first) .to receive(:to_formula).and_return(f_openssl) fa.audit_deps end it(:problems) { expect(f_a.problems).to be_empty } end describe "which is not allowlisted", :needs_macos do subject(:f_a) { fa } let(:fa) do formula_auditor "foo", <<~RUBY, new_formula: true, core_tap: true class Foo < Formula url "https://brew.sh/foo-1.0.tgz" homepage "https://brew.sh" depends_on "bc" end RUBY end let(:f_bc) do formula do url "https://brew.sh/bc-1.0.tgz" homepage "https://brew.sh" keg_only :provided_by_macos end end before do allow(fa.formula.deps.first) .to receive(:to_formula).and_return(f_bc) fa.audit_deps end it(:new_formula_problems) do expect(f_a.new_formula_problems) .to include(a_hash_including(message: a_string_matching(/is provided by macOS/))) end end end describe "dependency tag" do subject(:f_a) { fa } let(:core_tap) { false } let(:fa) do formula_auditor "foo", <<~RUBY, core_tap: class Foo < Formula url "https://brew.sh/foo-1.0.tgz"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
true
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_info_spec.rb
Library/Homebrew/test/formula_info_spec.rb
# frozen_string_literal: true require "formula_info" RSpec.describe FormulaInfo, :integration_test do it "tests the FormulaInfo class" do formula_path = setup_test_formula "testball" info = described_class.lookup(formula_path) expect(info).not_to be_nil expect(info.revision).to eq(0) expect(info.bottle_tags).to eq([]) expect(info.bottle_info).to be_nil expect(info.bottle_info_any).to be_nil expect(info.any_bottle_tag).to be_nil expect(info.version(:stable).to_s).to eq("0.1") version = info.version(:stable) expect(info.pkg_version).to eq(PkgVersion.new(version, 0)) end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/dependency_collector_spec.rb
Library/Homebrew/test/dependency_collector_spec.rb
# frozen_string_literal: true require "dependency_collector" RSpec.describe DependencyCollector do alias_matcher :be_a_build_requirement, :be_build subject(:collector) { described_class.new } def find_dependency(name) collector.deps.find { |dep| dep.name == name } end def find_requirement(klass) collector.requirements.find { |req| req.is_a? klass } end describe "#add" do specify "dependency creation" do collector.add "foo" => :build collector.add "bar" => ["--universal", :optional] expect(find_dependency("foo")).to be_an_instance_of(Dependency) expect(find_dependency("bar").tags.count).to eq(2) end it "returns the created dependency" do expect(collector.add("foo")).to eq(Dependency.new("foo")) end specify "requirement creation" do collector.add :xcode expect(find_requirement(XcodeRequirement)).to be_an_instance_of(XcodeRequirement) end it "deduplicates requirements" do 2.times { collector.add :xcode } expect(collector.requirements.count).to eq(1) end specify "requirement tags" do collector.add xcode: :build expect(find_requirement(XcodeRequirement)).to be_a_build_requirement end it "doesn't mutate the dependency spec" do spec = { "foo" => :optional } copy = spec.dup collector.add(spec) expect(spec).to eq(copy) end it "creates a resource dependency from a CVS URL" do resource = Resource.new resource.url(":pserver:anonymous:@brew.sh:/cvsroot/foo/bar", using: :cvs) expect(collector.add(resource)).to eq(Dependency.new("cvs", [:build, :test, :implicit])) end it "creates a resource dependency from a '.7z' URL" do resource = Resource.new resource.url("https://brew.sh/foo.7z") expect(collector.add(resource)).to eq(Dependency.new("p7zip", [:build, :test, :implicit])) end it "creates a resource dependency from a '.gz' URL" do resource = Resource.new resource.url("https://brew.sh/foo.tar.gz") expect(collector.add(resource)).to be_nil end it "creates a resource dependency from a '.lz' URL" do resource = Resource.new resource.url("https://brew.sh/foo.lz") expect(collector.add(resource)).to eq(Dependency.new("lzip", [:build, :test, :implicit])) end it "creates a resource dependency from a '.lha' URL" do resource = Resource.new resource.url("https://brew.sh/foo.lha") expect(collector.add(resource)).to eq(Dependency.new("lha", [:build, :test, :implicit])) end it "creates a resource dependency from a '.lzh' URL" do resource = Resource.new resource.url("https://brew.sh/foo.lzh") expect(collector.add(resource)).to eq(Dependency.new("lha", [:build, :test, :implicit])) end it "creates a resource dependency from a '.rar' URL" do resource = Resource.new resource.url("https://brew.sh/foo.rar") expect(collector.add(resource)).to eq(Dependency.new("libarchive", [:build, :test, :implicit])) end it "raises a TypeError for unknown classes" do expect { collector.add(Class.new) }.to raise_error(TypeError) end it "raises a TypeError for unknown Types" do expect { collector.add(Object.new) }.to raise_error(TypeError) end it "raises a TypeError for a Resource with an unknown download strategy" do resource = Resource.new resource.download_strategy = Class.new expect { collector.add(resource) }.to raise_error(TypeError) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/cask_dependent_spec.rb
Library/Homebrew/test/cask_dependent_spec.rb
# frozen_string_literal: true require "cask/cask_loader" require "cask_dependent" RSpec.describe CaskDependent, :needs_macos do subject(:dependent) { described_class.new test_cask } let :test_cask do Cask::CaskLoader.load(+<<-RUBY) cask "testing" do depends_on formula: "baz" depends_on cask: "foo-cask" depends_on macos: ">= :sequoia" end RUBY end describe "#deps" do it "is the formula dependencies of the cask" do expect(dependent.deps.map(&:name)) .to eq %w[baz] end end describe "#requirements" do it "is the requirements of the cask" do expect(dependent.requirements.map(&:name)) .to eq %w[foo-cask macos] end end describe "#recursive_dependencies", :integration_test, :no_api do it "is all the dependencies of the cask" do setup_test_formula "foo" setup_test_formula "bar" setup_test_formula "baz", <<-RUBY url "https://brew.sh/baz-1.0" depends_on "bar" RUBY expect(dependent.recursive_dependencies.map(&:name)) .to eq(%w[foo bar baz]) end end describe "#recursive_requirements", :integration_test do it "is all the dependencies of the cask" do setup_test_formula "foo" setup_test_formula "bar" setup_test_formula "baz", <<-RUBY url "https://brew.sh/baz-1.0" depends_on "bar" RUBY expect(dependent.recursive_requirements.map(&:name)) .to eq(%w[foo-cask macos]) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/ENV_spec.rb
Library/Homebrew/test/ENV_spec.rb
# frozen_string_literal: true require "extend/ENV" RSpec.describe "ENV" do shared_examples EnvActivation do subject(:env) { env_activation.extend(described_class) } let(:env_activation) { {}.extend(EnvActivation) } it "supports switching compilers" do subject.clang expect(subject["LD"]).to be_nil expect(subject["CC"]).to eq(subject["OBJC"]) end describe "#with_build_environment" do it "restores the environment" do before = subject.dup subject.with_build_environment do subject["foo"] = "bar" end expect(subject["foo"]).to be_nil expect(subject).to eq(before) end it "ensures the environment is restored" do before = subject.dup expect do subject.with_build_environment do subject["foo"] = "bar" raise StandardError end end.to raise_error(StandardError) expect(subject["foo"]).to be_nil expect(subject).to eq(before) end it "returns the value of the block" do expect(subject.with_build_environment { 1 }).to eq(1) end it "does not mutate the interface" do expected = subject.methods subject.with_build_environment do expect(subject.methods).to eq(expected) end expect(subject.methods).to eq(expected) end end describe "#append" do it "appends to an existing key" do subject["foo"] = "bar" subject.append "foo", "1" expect(subject["foo"]).to eq("bar 1") end it "appends to an existing empty key" do subject["foo"] = "" subject.append "foo", "1" expect(subject["foo"]).to eq("1") end it "appends to a non-existent key" do subject.append "foo", "1" expect(subject["foo"]).to eq("1") end # NOTE: This may be a wrong behavior; we should probably reject objects that # do not respond to `#to_str`. For now this documents existing behavior. it "coerces a value to a string" do subject.append "foo", 42 expect(subject["foo"]).to eq("42") end end describe "#prepend" do it "prepends to an existing key" do subject["foo"] = "bar" subject.prepend "foo", "1" expect(subject["foo"]).to eq("1 bar") end it "prepends to an existing empty key" do subject["foo"] = "" subject.prepend "foo", "1" expect(subject["foo"]).to eq("1") end it "prepends to a non-existent key" do subject.prepend "foo", "1" expect(subject["foo"]).to eq("1") end # NOTE: this may be a wrong behavior; we should probably reject objects that # do not respond to #to_str. For now this documents existing behavior. it "coerces a value to a string" do subject.prepend "foo", 42 expect(subject["foo"]).to eq("42") end end describe "#append_path" do it "appends to a path" do subject.append_path "FOO", "/usr/bin" expect(subject["FOO"]).to eq("/usr/bin") subject.append_path "FOO", "/bin" expect(subject["FOO"]).to eq("/usr/bin#{File::PATH_SEPARATOR}/bin") end end describe "#prepend_path" do it "prepends to a path" do subject.prepend_path "FOO", "/usr/local" expect(subject["FOO"]).to eq("/usr/local") subject.prepend_path "FOO", "/usr" expect(subject["FOO"]).to eq("/usr#{File::PATH_SEPARATOR}/usr/local") end end describe "#compiler" do it "allows switching compilers" do subject.public_send(:"gcc-9") expect(subject.compiler).to eq("gcc-9") end end example "deparallelize_block_form_restores_makeflags" do subject["MAKEFLAGS"] = "-j4" subject.deparallelize do expect(subject["MAKEFLAGS"]).to be_nil end expect(subject["MAKEFLAGS"]).to eq("-j4") end describe "#sensitive_environment" do it "list sensitive environment" do subject["SECRET_TOKEN"] = "password" expect(subject.sensitive_environment).to include("SECRET_TOKEN") end end describe "#clear_sensitive_environment!" do it "removes sensitive environment variables" do subject["SECRET_TOKEN"] = "password" subject.clear_sensitive_environment! expect(subject).not_to include("SECRET_TOKEN") end it "leaves non-sensitive environment variables alone" do subject["FOO"] = "bar" subject.clear_sensitive_environment! expect(subject["FOO"]).to eq "bar" end end end describe Stdenv do include_examples EnvActivation end describe Superenv do include_examples EnvActivation it "initializes deps" do expect(env.deps).to eq([]) expect(env.keg_only_deps).to eq([]) end describe "#cxx11" do it "supports gcc-11" do env["HOMEBREW_CC"] = "gcc-11" env.cxx11 expect(env["HOMEBREW_CCCFG"]).to include("x") expect(env["HOMEBREW_CCCFG"]).not_to include("g") end it "supports clang" do env["HOMEBREW_CC"] = "clang" env.cxx11 expect(env["HOMEBREW_CCCFG"]).to include("x") expect(env["HOMEBREW_CCCFG"]).to include("g") end end describe "#set_debug_symbols" do it "sets the debug symbols flag" do env.set_debug_symbols expect(env["HOMEBREW_CCCFG"]).to include("D") end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/attestation_spec.rb
Library/Homebrew/test/attestation_spec.rb
# frozen_string_literal: true require "diagnostic" RSpec.describe Homebrew::Attestation do let(:fake_gh) { Pathname.new("/extremely/fake/gh") } let(:fake_old_gh) { Pathname.new("/extremely/fake/old/gh") } let(:fake_gh_creds) { "fake-gh-api-token" } let(:fake_error_status) { instance_double(Process::Status, exitstatus: 1, termsig: nil) } let(:fake_auth_status) { instance_double(Process::Status, exitstatus: 4, termsig: nil) } let(:cached_download) { "/fake/cached/download" } let(:fake_bottle_filename) do instance_double(Bottle::Filename, name: "fakebottle", version: "1.0", to_s: "fakebottle--1.0.faketag.bottle.tar.gz") end let(:fake_bottle_url) { "https://example.com/#{fake_bottle_filename}" } let(:fake_bottle_tag) { instance_double(Utils::Bottles::Tag, to_sym: :faketag) } let(:fake_all_bottle_tag) { instance_double(Utils::Bottles::Tag, to_sym: :all) } let(:fake_bottle) do instance_double(Bottle, cached_download:, filename: fake_bottle_filename, url: fake_bottle_url, tag: fake_bottle_tag) end let(:fake_all_bottle) do instance_double(Bottle, cached_download:, filename: fake_bottle_filename, url: fake_bottle_url, tag: fake_all_bottle_tag) end let(:fake_result_invalid_json) { instance_double(SystemCommand::Result, stdout: "\"invalid JSON") } let(:fake_result_json_resp) do instance_double(SystemCommand::Result, stdout: JSON.dump([ { verificationResult: { verifiedTimestamps: [{ timestamp: "2024-03-13T00:00:00Z" }], statement: { subject: [{ name: fake_bottle_filename.to_s }] }, } }, ])) end let(:fake_result_json_resp_multi_subject) do instance_double(SystemCommand::Result, stdout: JSON.dump([ { verificationResult: { verifiedTimestamps: [{ timestamp: "2024-03-13T00:00:00Z" }], statement: { subject: [{ name: "nonsense" }, { name: fake_bottle_filename.to_s }] }, } }, ])) end let(:fake_result_json_resp_backfill) do digest = Digest::SHA256.hexdigest(fake_bottle_url) instance_double(SystemCommand::Result, stdout: JSON.dump([ { verificationResult: { verifiedTimestamps: [{ timestamp: "2024-03-13T00:00:00Z" }], statement: { subject: [{ name: "#{digest}--#{fake_bottle_filename}" }], }, } }, ])) end let(:fake_result_json_resp_too_new) do instance_double(SystemCommand::Result, stdout: JSON.dump([ { verificationResult: { verifiedTimestamps: [{ timestamp: "2024-03-15T00:00:00Z" }], statement: { subject: [{ name: fake_bottle_filename.to_s }] }, } }, ])) end let(:fake_json_resp_wrong_sub) do instance_double(SystemCommand::Result, stdout: JSON.dump([ { verificationResult: { verifiedTimestamps: [{ timestamp: "2024-03-13T00:00:00Z" }], statement: { subject: [{ name: "wrong-subject.tar.gz" }] }, } }, ])) end describe "::gh_executable" do it "calls ensure_executable" do expect(described_class).to receive(:ensure_executable!) .with("gh", reason: "verifying attestations", latest: true) .and_return(fake_gh) described_class.gh_executable end end # NOTE: `Homebrew::CLI::NamedArgs` will often return frozen arrays of formulae # so that's why we test with frozen arrays here. describe "::sort_formulae_for_install", :integration_test do let(:gh) { Formula["gh"] } let(:other) { Formula["other"] } before do setup_test_formula("gh") setup_test_formula("other") end context "when `gh` is in the formula list" do it "moves `gh` formulae to the front of the list" do expect(described_class).not_to receive(:gh_executable) [ [[gh], [gh]], [[gh, other], [gh, other]], [[other, gh], [gh, other]], ].each do |input, output| expect(described_class.sort_formulae_for_install(input.freeze)).to eq(output) end end end context "when the formula list is empty" do it "checks for the `gh` executable" do expect(described_class).to receive(:gh_executable).once expect(described_class.sort_formulae_for_install([].freeze)).to eq([]) end end context "when `gh` is not in the formula list" do it "checks for the `gh` executable" do expect(described_class).to receive(:gh_executable).once expect(described_class.sort_formulae_for_install([other].freeze)).to eq([other]) end end end describe "::check_attestation" do before do allow(described_class).to receive(:gh_executable) .and_return(fake_gh) end it "raises without any gh credentials" do expect(GitHub::API).to receive(:credentials) .and_return(nil) expect do described_class.check_attestation fake_bottle, described_class::HOMEBREW_CORE_REPO end.to raise_error(described_class::GhAuthNeeded) end it "raises when gh subprocess fails" do expect(GitHub::API).to receive(:credentials) .and_return(fake_gh_creds) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_raise(ErrorDuringExecution.new(["foo"], status: fake_error_status)) expect do described_class.check_attestation fake_bottle, described_class::HOMEBREW_CORE_REPO end.to raise_error(described_class::InvalidAttestationError) end it "raises auth error when gh subprocess fails with auth exit code" do expect(GitHub::API).to receive(:credentials) .and_return(fake_gh_creds) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_raise(ErrorDuringExecution.new(["foo"], status: fake_auth_status)) expect do described_class.check_attestation fake_bottle, described_class::HOMEBREW_CORE_REPO end.to raise_error(described_class::GhAuthInvalid) end it "raises when gh returns invalid JSON" do expect(GitHub::API).to receive(:credentials) .and_return(fake_gh_creds) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_return(fake_result_invalid_json) expect do described_class.check_attestation fake_bottle, described_class::HOMEBREW_CORE_REPO end.to raise_error(described_class::InvalidAttestationError) end it "raises when gh returns other subjects" do expect(GitHub::API).to receive(:credentials) .and_return(fake_gh_creds) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_return(fake_json_resp_wrong_sub) expect do described_class.check_attestation fake_bottle, described_class::HOMEBREW_CORE_REPO end.to raise_error(described_class::InvalidAttestationError) end it "checks subject prefix when the bottle is an :all bottle" do expect(GitHub::API).to receive(:credentials) .and_return(fake_gh_creds) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_return(fake_result_json_resp) described_class.check_attestation fake_all_bottle, described_class::HOMEBREW_CORE_REPO end end describe "::check_core_attestation" do before do allow(described_class).to receive(:gh_executable) .and_return(fake_gh) allow(GitHub::API).to receive(:credentials) .and_return(fake_gh_creds) end it "calls gh with args for homebrew-core" do expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_return(fake_result_json_resp) described_class.check_core_attestation fake_bottle end it "calls gh with args for homebrew-core and handles a multi-subject attestation" do expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_return(fake_result_json_resp_multi_subject) described_class.check_core_attestation fake_bottle end it "calls gh with args for backfill when homebrew-core attestation is missing" do expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .once .and_raise(described_class::MissingAttestationError) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::BACKFILL_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .and_return(fake_result_json_resp_backfill) described_class.check_core_attestation fake_bottle end it "raises when the backfilled attestation is too new" do expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::HOMEBREW_CORE_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .exactly(described_class::ATTESTATION_MAX_RETRIES + 1) .and_raise(described_class::MissingAttestationError) expect(described_class).to receive(:system_command!) .with(fake_gh, args: ["attestation", "verify", cached_download, "--repo", described_class::BACKFILL_REPO, "--format", "json"], env: { "GH_TOKEN" => fake_gh_creds, "GH_HOST" => "github.com" }, secrets: [fake_gh_creds], print_stderr: false, chdir: HOMEBREW_TEMP) .exactly(described_class::ATTESTATION_MAX_RETRIES + 1) .and_return(fake_result_json_resp_too_new) expect do described_class.check_core_attestation fake_bottle end.to raise_error(described_class::InvalidAttestationError) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/tab_spec.rb
Library/Homebrew/test/tab_spec.rb
# frozen_string_literal: true require "tab" require "formula" RSpec.describe Tab do alias_matcher :be_built_with, :be_with matcher :be_poured_from_bottle do match do |actual| actual.poured_from_bottle == true end end matcher :be_built_as_bottle do match do |actual| actual.built_as_bottle == true end end matcher :be_installed_as_dependency do match do |actual| actual.installed_as_dependency == true end end matcher :be_installed_on_request do match do |actual| actual.installed_on_request == true end end matcher :be_loaded_from_api do match do |actual| actual.loaded_from_api == true end end subject(:tab) do described_class.new( "homebrew_version" => HOMEBREW_VERSION, "used_options" => used_options.as_flags, "unused_options" => unused_options.as_flags, "built_as_bottle" => false, "poured_from_bottle" => true, "installed_as_dependency" => false, "installed_on_request" => true, "changed_files" => [], "time" => time, "source_modified_time" => 0, "compiler" => "clang", "stdlib" => "libcxx", "runtime_dependencies" => [], "source" => { "tap" => CoreTap.instance.to_s, "path" => CoreTap.instance.path.to_s, "spec" => "stable", "versions" => { "stable" => "0.10", "head" => "HEAD-1111111", }, }, "arch" => Hardware::CPU.arch, "built_on" => DevelopmentTools.build_system_info, ) end let(:time) { Time.now.to_i } let(:unused_options) { Options.create(%w[--with-baz --without-qux]) } let(:used_options) { Options.create(%w[--with-foo --without-bar]) } let(:f) { formula { url "foo-1.0" } } let(:f_tab_path) { f.prefix/"INSTALL_RECEIPT.json" } let(:f_tab_content) { (TEST_FIXTURE_DIR/"receipt.json").read } specify "defaults" do # < 1.1.7 runtime_dependencies were wrong so are ignored stub_const("HOMEBREW_VERSION", "1.1.7") tab = described_class.empty expect(tab.homebrew_version).to eq(HOMEBREW_VERSION) expect(tab.unused_options).to be_empty expect(tab.used_options).to be_empty expect(tab.changed_files).to be_nil expect(tab).not_to be_built_as_bottle expect(tab).not_to be_poured_from_bottle expect(tab).not_to be_installed_as_dependency expect(tab).not_to be_installed_on_request expect(tab).not_to be_loaded_from_api expect(tab).to be_stable expect(tab).not_to be_head expect(tab.tap).to be_nil expect(tab.time).to be_nil expect(tab.runtime_dependencies).to be_nil expect(tab.stable_version).to be_nil expect(tab.head_version).to be_nil expect(tab.cxxstdlib.compiler).to eq(DevelopmentTools.default_compiler) expect(tab.cxxstdlib.type).to be_nil expect(tab.source["path"]).to be_nil end specify "#include?" do expect(tab).to include("with-foo") expect(tab).to include("without-bar") end specify "#with?" do # rubocop:todo RSpec/AggregateExamples expect(tab).to be_built_with("foo") expect(tab).to be_built_with("qux") expect(tab).not_to be_built_with("bar") expect(tab).not_to be_built_with("baz") end specify "#parsed_homebrew_version" do tab = described_class.new expect(tab.parsed_homebrew_version).to be Version::NULL tab = described_class.new(homebrew_version: "1.2.3") expect(tab.parsed_homebrew_version).to eq("1.2.3") expect(tab.parsed_homebrew_version).to be < "1.2.3-1-g12789abdf" expect(tab.parsed_homebrew_version).to be_a(Version) tab.homebrew_version = "1.2.4-567-g12789abdf" expect(tab.parsed_homebrew_version).to be > "1.2.4" expect(tab.parsed_homebrew_version).to be > "1.2.4-566-g21789abdf" expect(tab.parsed_homebrew_version).to be < "1.2.4-568-g01789abdf" tab = described_class.new(homebrew_version: "2.0.0-134-gabcdefabc-dirty") expect(tab.parsed_homebrew_version).to be > "2.0.0" expect(tab.parsed_homebrew_version).to be > "2.0.0-133-g21789abdf" expect(tab.parsed_homebrew_version).to be < "2.0.0-135-g01789abdf" end specify "#runtime_dependencies" do tab = described_class.new expect(tab.runtime_dependencies).to be_nil tab.homebrew_version = "1.1.6" expect(tab.runtime_dependencies).to be_nil tab.runtime_dependencies = [] expect(tab.runtime_dependencies).not_to be_nil tab.homebrew_version = "1.1.5" expect(tab.runtime_dependencies).to be_nil tab.homebrew_version = "1.1.7" expect(tab.runtime_dependencies).not_to be_nil tab.homebrew_version = "1.1.10" expect(tab.runtime_dependencies).not_to be_nil tab.runtime_dependencies = [{ "full_name" => "foo", "version" => "1.0" }] expect(tab.runtime_dependencies).not_to be_nil end describe "::runtime_deps_hash" do it "handles older Homebrew versions correctly" do runtime_deps = [Dependency.new("foo")] foo = formula("foo") { url "foo-1.0" } stub_formula_loader foo runtime_deps_hash = described_class.runtime_deps_hash(foo, runtime_deps) tab = described_class.new tab.homebrew_version = "1.1.6" tab.runtime_dependencies = runtime_deps_hash expect(tab.runtime_dependencies).to eql( [{ "full_name" => "foo", "version" => "1.0", "revision" => 0, "pkg_version" => "1.0", "declared_directly" => false }], ) end it "include declared dependencies" do foo = formula("foo") { url "foo-1.0" } stub_formula_loader foo runtime_deps = [Dependency.new("foo")] formula = instance_double(Formula, deps: runtime_deps) expected_output = [ { "full_name" => "foo", "version" => "1.0", "revision" => 0, "pkg_version" => "1.0", "declared_directly" => true, }, ] expect(described_class.runtime_deps_hash(formula, runtime_deps)).to eq(expected_output) end it "includes recursive dependencies" do foo = formula("foo") { url "foo-1.0" } bar = formula("bar") { url "bar-2.0" } stub_formula_loader foo stub_formula_loader bar # Simulating dependencies formula => foo => bar formula_declared_deps = [Dependency.new("foo")] formula_recursive_deps = [Dependency.new("foo"), Dependency.new("bar")] formula = instance_double(Formula, deps: formula_declared_deps) expected_output = [ { "full_name" => "foo", "version" => "1.0", "revision" => 0, "pkg_version" => "1.0", "declared_directly" => true, }, { "full_name" => "bar", "version" => "2.0", "revision" => 0, "pkg_version" => "2.0", "declared_directly" => false, }, ] expect(described_class.runtime_deps_hash(formula, formula_recursive_deps)).to eq(expected_output) end it "includes compatibility_version when set" do foo = formula("foo") do url "foo-1.0" compatibility_version 1 end stub_formula_loader foo formula_declared_deps = [Dependency.new("foo")] formula_recursive_deps = [Dependency.new("foo")] formula = instance_double(Formula, deps: formula_declared_deps) expected_output = [ { "full_name" => "foo", "version" => "1.0", "revision" => 0, "pkg_version" => "1.0", "declared_directly" => true, "compatibility_version" => 1, }, ] expect(described_class.runtime_deps_hash(formula, formula_recursive_deps)).to eq(expected_output) end end specify "#cxxstdlib" do # rubocop:todo RSpec/AggregateExamples expect(tab.cxxstdlib.compiler).to eq(:clang) expect(tab.cxxstdlib.type).to eq(:libcxx) end specify "other attributes" do # rubocop:todo RSpec/AggregateExamples expect(tab.tap.name).to eq("homebrew/core") expect(tab.time).to eq(time) expect(tab).not_to be_built_as_bottle expect(tab).to be_poured_from_bottle expect(tab).not_to be_installed_as_dependency expect(tab).to be_installed_on_request expect(tab).not_to be_loaded_from_api end describe "::from_file" do it "parses a formula Tab from a file" do path = Pathname.new("#{TEST_FIXTURE_DIR}/receipt.json") tab = described_class.from_file(path) source_path = "/usr/local/Library/Taps/homebrew/homebrew-core/Formula/foo.rb" runtime_dependencies = [{ "full_name" => "foo", "version" => "1.0" }] changed_files = %w[INSTALL_RECEIPT.json bin/foo].map { Pathname.new(it) } expect(tab.used_options.sort).to eq(used_options.sort) expect(tab.unused_options.sort).to eq(unused_options.sort) expect(tab.changed_files).to eq(changed_files) expect(tab).not_to be_built_as_bottle expect(tab).to be_poured_from_bottle expect(tab).not_to be_installed_as_dependency expect(tab).to be_installed_on_request expect(tab).not_to be_loaded_from_api expect(tab).to be_stable expect(tab).not_to be_head expect(tab.tap.name).to eq("homebrew/core") expect(tab.spec).to eq(:stable) expect(tab.time).to eq(Time.at(1_403_827_774).to_i) expect(tab.cxxstdlib.compiler).to eq(:clang) expect(tab.cxxstdlib.type).to eq(:libcxx) expect(tab.runtime_dependencies).to eq(runtime_dependencies) expect(tab.stable_version.to_s).to eq("2.14") expect(tab.head_version.to_s).to eq("HEAD-0000000") expect(tab.source["path"]).to eq(source_path) end end describe "::from_file_content" do it "parses a formula Tab from a file" do path = Pathname.new("#{TEST_FIXTURE_DIR}/receipt.json") tab = described_class.from_file_content(path.read, path) source_path = "/usr/local/Library/Taps/homebrew/homebrew-core/Formula/foo.rb" runtime_dependencies = [{ "full_name" => "foo", "version" => "1.0" }] changed_files = %w[INSTALL_RECEIPT.json bin/foo].map { Pathname.new(it) } expect(tab.used_options.sort).to eq(used_options.sort) expect(tab.unused_options.sort).to eq(unused_options.sort) expect(tab.changed_files).to eq(changed_files) expect(tab).not_to be_built_as_bottle expect(tab).to be_poured_from_bottle expect(tab).not_to be_installed_as_dependency expect(tab).to be_installed_on_request expect(tab).not_to be_loaded_from_api expect(tab).to be_stable expect(tab).not_to be_head expect(tab.tap.name).to eq("homebrew/core") expect(tab.spec).to eq(:stable) expect(tab.time).to eq(Time.at(1_403_827_774).to_i) expect(tab.cxxstdlib.compiler).to eq(:clang) expect(tab.cxxstdlib.type).to eq(:libcxx) expect(tab.runtime_dependencies).to eq(runtime_dependencies) expect(tab.stable_version.to_s).to eq("2.14") expect(tab.head_version.to_s).to eq("HEAD-0000000") expect(tab.source["path"]).to eq(source_path) end it "can parse an old formula Tab file" do path = Pathname.new("#{TEST_FIXTURE_DIR}/receipt_old.json") tab = described_class.from_file_content(path.read, path) expect(tab.used_options.sort).to eq(used_options.sort) expect(tab.unused_options.sort).to eq(unused_options.sort) expect(tab).not_to be_built_as_bottle expect(tab).to be_poured_from_bottle expect(tab).not_to be_installed_as_dependency expect(tab).not_to be_installed_on_request expect(tab).not_to be_loaded_from_api expect(tab).to be_stable expect(tab).not_to be_head expect(tab.tap.name).to eq("homebrew/core") expect(tab.spec).to eq(:stable) expect(tab.time).to eq(Time.at(1_403_827_774).to_i) expect(tab.cxxstdlib.compiler).to eq(:clang) expect(tab.cxxstdlib.type).to eq(:libcxx) expect(tab.runtime_dependencies).to be_nil end it "raises a parse exception message including the Tab filename" do expect { described_class.from_file_content("''", "receipt.json") }.to raise_error( JSON::ParserError, /receipt.json:/, ) end end describe "::create" do it "creates a formula Tab" do # < 1.1.7 runtime dependencies were wrong so are ignored stub_const("HOMEBREW_VERSION", "1.1.7") # don't try to load gcc/glibc allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false) f = formula do url "foo-1.0" depends_on "bar" depends_on "user/repo/from_tap" depends_on "baz" => :build end tap = Tap.fetch("user", "repo") from_tap = formula("from_tap", path: tap.path/"Formula/from_tap.rb") do url "from_tap-1.0" revision 1 end stub_formula_loader from_tap stub_formula_loader formula("bar") { url "bar-2.0" } stub_formula_loader formula("baz") { url "baz-3.0" } compiler = DevelopmentTools.default_compiler stdlib = :libcxx tab = described_class.create(f, compiler, stdlib) runtime_dependencies = [ { "full_name" => "bar", "version" => "2.0", "revision" => 0, "pkg_version" => "2.0", "declared_directly" => true }, { "full_name" => "user/repo/from_tap", "version" => "1.0", "revision" => 1, "pkg_version" => "1.0_1", "declared_directly" => true }, ] expect(tab.runtime_dependencies).to eq(runtime_dependencies) expect(tab.source["path"]).to eq(f.path.to_s) end it "can create a formula Tab from an alias" do alias_path = CoreTap.instance.alias_dir/"bar" f = formula(alias_path:) { url "foo-1.0" } compiler = DevelopmentTools.default_compiler stdlib = :libcxx tab = described_class.create(f, compiler, stdlib) expect(tab.source["path"]).to eq(f.alias_path.to_s) end end describe "::for_keg" do subject(:tab_for_keg) { described_class.for_keg(f.prefix) } it "creates a Tab for a given Keg" do f.prefix.mkpath f_tab_path.write f_tab_content expect(tab_for_keg.tabfile).to eq(f_tab_path) end it "can create a Tab for a non-existent Keg" do f.prefix.mkpath expect(tab_for_keg.tabfile).to eq(f_tab_path) end end describe "::for_formula" do it "creates a Tab for a given Formula" do tab = described_class.for_formula(f) expect(tab.source["path"]).to eq(f.path.to_s) end it "can create a Tab for for a Formula from an alias" do alias_path = CoreTap.instance.alias_dir/"bar" f = formula(alias_path:) { url "foo-1.0" } tab = described_class.for_formula(f) expect(tab.source["path"]).to eq(alias_path.to_s) end it "creates a Tab for a given Formula with existing Tab" do f.prefix.mkpath f_tab_path.write f_tab_content tab = described_class.for_formula(f) expect(tab.tabfile).to eq(f_tab_path) end it "can create a Tab for a non-existent Formula" do f.prefix.mkpath tab = described_class.for_formula(f) expect(tab.tabfile).to be_nil end it "can create a Tab for a Formula with multiple Kegs" do f.prefix.mkpath f_tab_path.write f_tab_content f2 = formula { url "foo-2.0" } f2.prefix.mkpath expect(f2.rack).to eq(f.rack) expect(f.installed_prefixes.length).to eq(2) tab = described_class.for_formula(f) expect(tab.tabfile).to eq(f_tab_path) end it "can create a Tab for a Formula with an outdated Kegs" do f.prefix.mkpath f_tab_path.write f_tab_content f2 = formula { url "foo-2.0" } expect(f2.rack).to eq(f.rack) expect(f.installed_prefixes.length).to eq(1) tab = described_class.for_formula(f) expect(tab.tabfile).to eq(f_tab_path) end end specify "#to_json" do json_tab = described_class.new(JSON.parse(tab.to_json)) expect(json_tab.homebrew_version).to eq(tab.homebrew_version) expect(json_tab.used_options.sort).to eq(tab.used_options.sort) expect(json_tab.unused_options.sort).to eq(tab.unused_options.sort) expect(json_tab.built_as_bottle).to eq(tab.built_as_bottle) expect(json_tab.poured_from_bottle).to eq(tab.poured_from_bottle) expect(json_tab.changed_files).to eq(tab.changed_files) expect(json_tab.tap).to eq(tab.tap) expect(json_tab.spec).to eq(tab.spec) expect(json_tab.time).to eq(tab.time) expect(json_tab.compiler).to eq(tab.compiler) expect(json_tab.stdlib).to eq(tab.stdlib) expect(json_tab.runtime_dependencies).to eq(tab.runtime_dependencies) expect(json_tab.stable_version).to eq(tab.stable_version) expect(json_tab.head_version).to eq(tab.head_version) expect(json_tab.source["path"]).to eq(tab.source["path"]) expect(json_tab.arch).to eq(tab.arch.to_s) expect(json_tab.built_on["os"]).to eq(tab.built_on["os"]) end specify "#to_bottle_hash" do json_tab = described_class.new(JSON.parse(tab.to_bottle_hash.to_json)) expect(json_tab.homebrew_version).to eq(tab.homebrew_version) expect(json_tab.changed_files).to eq(tab.changed_files) expect(json_tab.source_modified_time).to eq(tab.source_modified_time) expect(json_tab.stdlib).to eq(tab.stdlib) expect(json_tab.compiler).to eq(tab.compiler) expect(json_tab.runtime_dependencies).to eq(tab.runtime_dependencies) expect(json_tab.arch).to eq(tab.arch.to_s) expect(json_tab.built_on["os"]).to eq(tab.built_on["os"]) end describe "#to_s" do let(:time_string) { Time.at(1_720_189_863).strftime("%Y-%m-%d at %H:%M:%S") } it "returns install information for the Tab" do tab = described_class.new( poured_from_bottle: true, loaded_from_api: true, time: 1_720_189_863, used_options: %w[--with-foo --without-bar], ) output = "Poured from bottle using the formulae.brew.sh API on #{time_string} " \ "with: --with-foo --without-bar" expect(tab.to_s).to eq(output) end it "includes 'Poured from bottle' if the formula was installed from a bottle" do tab = described_class.new(poured_from_bottle: true) expect(tab.to_s).to include("Poured from bottle") end it "includes 'Built from source' if the formula was not installed from a bottle" do tab = described_class.new(poured_from_bottle: false) expect(tab.to_s).to include("Built from source") end it "includes 'using the formulae.brew.sh API' if the formula was installed from the API" do tab = described_class.new(loaded_from_api: true) expect(tab.to_s).to include("using the formulae.brew.sh API") end it "does not include 'using the formulae.brew.sh API' if the formula was not installed from the API" do tab = described_class.new(loaded_from_api: false) expect(tab.to_s).not_to include("using the formulae.brew.sh API") end it "includes the time value if specified" do tab = described_class.new(time: 1_720_189_863) expect(tab.to_s).to include("on #{time_string}") end it "does not include the time value if not specified" do tab = described_class.new(time: nil) expect(tab.to_s).not_to match(/on %d+-%d+-%d+ at %d+:%d+:%d+/) end it "includes options if specified" do tab = described_class.new(used_options: %w[--with-foo --without-bar]) expect(tab.to_s).to include("with: --with-foo --without-bar") end it "not to include options if not specified" do tab = described_class.new(used_options: []) expect(tab.to_s).not_to include("with: ") end end specify "::remap_deprecated_options" do deprecated_options = [DeprecatedOption.new("with-foo", "with-foo-new")] remapped_options = described_class.remap_deprecated_options(deprecated_options, tab.used_options) expect(remapped_options).to include(Option.new("without-bar")) expect(remapped_options).to include(Option.new("with-foo-new")) end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_validation_spec.rb
Library/Homebrew/test/formula_validation_spec.rb
# frozen_string_literal: true require "formula" RSpec.describe Formula do describe "::new" do matcher :fail_with_invalid do |attr| match do |actual| expect do actual.call rescue => e expect(e.attr).to eq(attr) raise e end.to raise_error(FormulaValidationError) end def supports_block_expectations? true end end it "can't override the `brew` method" do expect do formula do def brew; end end end.to raise_error(RuntimeError, /\AThe method `brew` on #{described_class} was declared as final/) end it "validates the `name`" do expect do formula "name with spaces" do url "foo" version "1.0" end end.to fail_with_invalid :name end it "validates the `url`" do expect do formula do url "" version "1" end end.to fail_with_invalid :url end it "validates the `version`" do expect do formula do url "foo" version "version with spaces" end end.to fail_with_invalid :version expect do formula do url "foo" version "" end end.to fail_with_invalid :version expect do formula do url "foo" version nil end end.to fail_with_invalid :version end specify "HEAD-only is valid" do f = formula do head "foo" end expect(f).to be_head end it "fails when Formula is empty" do expect do formula do # do nothing end end.to raise_error(FormulaSpecificationError) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/cleaner_spec.rb
Library/Homebrew/test/cleaner_spec.rb
# frozen_string_literal: true require "cleaner" require "formula" RSpec.describe Cleaner do include FileUtils describe "#clean" do subject(:cleaner) { described_class.new(f) } let(:f) { formula("cleaner_test") { url "foo-1.0" } } before do f.prefix.mkpath end it "cleans files" do f.bin.mkpath f.lib.mkpath if OS.mac? cp "#{TEST_FIXTURE_DIR}/mach/a.out", f.bin cp Dir["#{TEST_FIXTURE_DIR}/mach/*.dylib"], f.lib elsif OS.linux? cp "#{TEST_FIXTURE_DIR}/elf/hello", f.bin cp Dir["#{TEST_FIXTURE_DIR}/elf/libhello.so.0"], f.lib end cleaner.clean if OS.mac? expect((f.bin/"a.out").stat.mode).to eq(0100555) expect((f.lib/"fat.dylib").stat.mode).to eq(0100444) expect((f.lib/"x86_64.dylib").stat.mode).to eq(0100444) expect((f.lib/"i386.dylib").stat.mode).to eq(0100444) elsif OS.linux? expect((f.bin/"hello").stat.mode).to eq(0100555) expect((f.lib/"libhello.so.0").stat.mode).to eq(0100555) end end it "prunes the prefix if it is empty" do cleaner.clean expect(f.prefix).not_to be_a_directory end it "prunes empty directories" do subdir = f.bin/"subdir" subdir.mkpath cleaner.clean expect(f.bin).not_to be_a_directory expect(subdir).not_to be_a_directory end it "removes a symlink when its target was pruned before" do dir = f.prefix/"b" symlink = f.prefix/"a" dir.mkpath ln_s dir.basename, symlink cleaner.clean expect(dir).not_to exist expect(symlink).not_to be_a_symlink expect(symlink).not_to exist end it "removes symlinks pointing to an empty directory" do dir = f.prefix/"b" symlink = f.prefix/"c" dir.mkpath ln_s dir.basename, symlink cleaner.clean expect(dir).not_to exist expect(symlink).not_to be_a_symlink expect(symlink).not_to exist end it "removes broken symlinks" do symlink = f.prefix/"symlink" ln_s "target", symlink cleaner.clean expect(symlink).not_to be_a_symlink end it "removes '.la' files" do file = f.lib/"foo.la" file.dirname.mkpath touch file cleaner.clean expect(file).not_to exist end it "removes 'perllocal' files" do file = f.lib/"perl5/darwin-thread-multi-2level/perllocal.pod" file.dirname.mkpath touch file cleaner.clean expect(file).not_to exist end it "removes '.packlist' files" do file = f.lib/"perl5/darwin-thread-multi-2level/auto/test/.packlist" file.dirname.mkpath touch file cleaner.clean expect(file).not_to exist end it "removes 'charset.alias' files" do file = f.lib/"charset.alias" file.dirname.mkpath touch file cleaner.clean expect(file).not_to exist end it "removes 'info/**/dir' files except for 'info/<name>/dir'" do file = f.info/"dir" arch_file = f.info/"i686-elf/dir" name_file = f.info/f.name/"dir" file.dirname.mkpath arch_file.dirname.mkpath name_file.dirname.mkpath touch file touch arch_file touch name_file cleaner.clean expect(file).not_to exist expect(arch_file).not_to exist expect(name_file).to exist end it "removes '*.dist-info/direct_url.json' files" do dir = f.lib/"python3.12/site-packages/test.dist-info" file = dir/"direct_url.json" unrelated_file = dir/"METADATA" unrelated_dir_file = f.lib/"direct_url.json" dir.mkpath touch file touch unrelated_file touch unrelated_dir_file cleaner.clean expect(file).not_to exist expect(unrelated_file).to exist expect(unrelated_dir_file).to exist end it "removes '*.dist-info/RECORD' files" do dir = f.lib/"python3.12/site-packages/test.dist-info" file = dir/"RECORD" unrelated_file = dir/"METADATA" unrelated_dir_file = f.lib/"RECORD" dir.mkpath touch file touch unrelated_file touch unrelated_dir_file cleaner.clean expect(file).not_to exist expect(unrelated_file).to exist expect(unrelated_dir_file).to exist end it "modifies '*.dist-info/INSTALLER' files" do file = f.lib/"python3.12/site-packages/test.dist-info/INSTALLER" file.dirname.mkpath file.write "pip\n" cleaner.clean expect(file.read).to eq "brew\n" end end describe "::skip_clean" do def stub_formula_skip_clean(skip_paths) formula("cleaner_test") do url "foo-1.0" skip_clean skip_paths end end it "adds paths that should be skipped" do f = stub_formula_skip_clean("bin") f.bin.mkpath described_class.new(f).clean expect(f.bin).to be_a_directory end it "also skips empty sub-directories under the added paths" do f = stub_formula_skip_clean("bin") subdir = f.bin/"subdir" subdir.mkpath described_class.new(f).clean expect(f.bin).to be_a_directory expect(subdir).to be_a_directory end it "allows skipping broken symlinks" do f = stub_formula_skip_clean("symlink") f.prefix.mkpath symlink = f.prefix/"symlink" ln_s "target", symlink described_class.new(f).clean expect(symlink).to be_a_symlink end it "allows skipping symlinks pointing to an empty directory" do f = stub_formula_skip_clean("c") dir = f.prefix/"b" symlink = f.prefix/"c" dir.mkpath ln_s dir.basename, symlink described_class.new(f).clean expect(dir).not_to exist expect(symlink).to be_a_symlink expect(symlink).not_to exist end it "allows skipping symlinks whose target was pruned before" do f = stub_formula_skip_clean("a") dir = f.prefix/"b" symlink = f.prefix/"a" dir.mkpath ln_s dir.basename, symlink described_class.new(f).clean expect(dir).not_to exist expect(symlink).to be_a_symlink expect(symlink).not_to exist end it "allows skipping '.la' files" do f = stub_formula_skip_clean(:la) file = f.lib/"foo.la" f.lib.mkpath touch file described_class.new(f).clean expect(file).to exist end it "allows skipping sub-directories" do f = stub_formula_skip_clean("lib/subdir") dir = f.lib/"subdir" dir.mkpath described_class.new(f).clean expect(dir).to be_a_directory end it "allows skipping paths relative to prefix" do f = stub_formula_skip_clean("bin/a") dir1 = f.bin/"a" dir2 = f.lib/"bin/a" dir1.mkpath dir2.mkpath described_class.new(f).clean expect(dir1).to exist expect(dir2).not_to 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/test/system_command_spec.rb
Library/Homebrew/test/system_command_spec.rb
# frozen_string_literal: true require "system_command" RSpec.describe SystemCommand do describe "#initialize" do subject(:command) do described_class.new( "env", args: env_args, env:, must_succeed: true, sudo:, sudo_as_root:, ) end let(:env_args) { ["bash", "-c", 'printf "%s" "${A?}" "${B?}" "${C?}"'] } let(:env) { { "A" => "1", "B" => "2", "C" => "3" } } let(:sudo) { false } let(:sudo_as_root) { false } context "when given some environment variables" do it("run!.stdout") { expect(command.run!.stdout).to eq("123") } describe "the resulting command line" do it "includes the given variables explicitly" do expect(command) .to receive(:exec3) .with( an_instance_of(Hash), "/usr/bin/env", "A=1", "B=2", "C=3", "env", *env_args, pgroup: true ) .and_call_original command.run! end end end context "when given an environment variable which is set to nil" do let(:env) { { "A" => "1", "B" => "2", "C" => nil } } it "unsets them" do expect do command.run! end.to raise_error(/C: parameter (null or )?not set/) end end context "when given some environment variables and sudo: true, sudo_as_root: false" do let(:sudo) { true } let(:sudo_as_root) { false } describe "the resulting command line" do it "includes the given variables explicitly" do expect(command) .to receive(:exec3) .with( an_instance_of(Hash), "/usr/bin/sudo", "-E", "A=1", "B=2", "C=3", "--", "env", *env_args, pgroup: nil ) .and_wrap_original do |original_exec3, *_, &block| original_exec3.call({}, "true", &block) end command.run! end end end context "when given some environment variables and sudo: true, sudo_as_root: true" do let(:sudo) { true } let(:sudo_as_root) { true } describe "the resulting command line" do it "includes the given variables explicitly" do expect(command) .to receive(:exec3) .with( an_instance_of(Hash), "/usr/bin/sudo", "-u", "root", "-E", "A=1", "B=2", "C=3", "--", "env", *env_args, pgroup: nil ) .and_wrap_original do |original_exec3, *_, &block| original_exec3.call({}, "true", &block) end command.run! end end end end context "when the exit code is 0" do describe "its result" do subject(:result) { described_class.run("true") } it { is_expected.to be_a_success } it(:exit_status) { expect(result.exit_status).to eq(0) } end end context "when the exit code is 1" do let(:command) { "false" } context "with a command that must succeed" do it "throws an error" do expect do described_class.run!(command) end.to raise_error(ErrorDuringExecution) end end context "with a command that does not have to succeed" do describe "its result" do subject(:result) { described_class.run(command) } it { is_expected.not_to be_a_success } it(:exit_status) { expect(result.exit_status).to eq(1) } end end end context "when given a pathname" do let(:command) { "/bin/ls" } let(:path) { Pathname(Dir.mktmpdir) } before do FileUtils.touch(path.join("somefile")) end describe "its result" do subject(:result) { described_class.run(command, args: [path]) } it { is_expected.to be_a_success } it(:stdout) { expect(result.stdout).to eq("somefile\n") } end end context "with both STDOUT and STDERR output from upstream" do let(:command) { "/bin/bash" } let(:options) do { args: [ "-c", "for i in $(seq 1 2 5); do echo $i; echo $(($i + 1)) >&2; done", ] } end shared_examples "it returns '1 2 3 4 5 6'" do describe "its result" do subject(:result) { described_class.run(command, **options) } it { is_expected.to be_a_success } it(:stdout) { expect(result.stdout).to eq([1, 3, 5, nil].join("\n")) } it(:stderr) { expect(result.stderr).to eq([2, 4, 6, nil].join("\n")) } end end context "with default options" do it "echoes only STDERR" do expected = [2, 4, 6].map { |i| "#{i}\n" }.join expect do described_class.run(command, **options) end.to output(expected).to_stderr end include_examples("it returns '1 2 3 4 5 6'") end context "with `print_stdout: true`" do before do options.merge!(print_stdout: true) end it "echoes both STDOUT and STDERR" do expect { described_class.run(command, **options) } .to output("1\n3\n5\n").to_stdout .and output("2\n4\n6\n").to_stderr end include_examples("it returns '1 2 3 4 5 6'") end context "with `print_stdout: :debug`" do before do options.merge!(print_stdout: :debug) end it "echoes only STDERR output" do expect { described_class.run(command, **options) } .to output("2\n4\n6\n").to_stderr .and not_to_output.to_stdout end context "when `verbose?` and `debug?` are true" do include Context let(:options) do { args: [ "-c", "for i in $(seq 1 2 5); do echo $i; sleep 0.1; echo $(($i + 1)) >&2; sleep 0.1; done", ] } end it "echoes the command and all output to STDERR" do with_context(verbose: true, debug: true) do expect { described_class.run(command, **options) } .to output(/\A.*#{Regexp.escape(command)}.*\n1\n2\n3\n4\n5\n6\n\Z/).to_stderr .and not_to_output.to_stdout end end end include_examples("it returns '1 2 3 4 5 6'") end context "with `print_stderr: false`" do before do options.merge!(print_stderr: false) end it "echoes nothing" do expect do described_class.run(command, **options) end.not_to output.to_stdout end include_examples("it returns '1 2 3 4 5 6'") end context "with `print_stdout: true` and `print_stderr: false`" do before do options.merge!(print_stdout: true, print_stderr: false) end it "echoes only STDOUT" do expected = [1, 3, 5].map { |i| "#{i}\n" }.join expect do described_class.run(command, **options) end.to output(expected).to_stdout end include_examples("it returns '1 2 3 4 5 6'") end end context "with a very long STDERR output" do let(:command) { "/bin/bash" } let(:options) do { args: [ "-c", "for i in $(seq 1 2 100000); do echo $i; echo $(($i + 1)) >&2; done", ] } end it "returns without deadlocking", timeout: 30 do expect(described_class.run(command, **options)).to be_a_success end end context "when given an invalid variable name" do it "raises an ArgumentError" do expect { described_class.run("true", env: { "1ABC" => true }) } .to raise_error(ArgumentError, /variable name/) end end it "looks for executables in a custom PATH" do mktmpdir do |path| (path/"tool").write <<~SH #!/bin/sh echo Hello, world! SH FileUtils.chmod "+x", path/"tool" expect(described_class.run("tool", env: { "PATH" => path.to_s }).stdout).to include "Hello, world!" end end describe "#run" do it "does not raise a `SystemCallError` when the executable does not exist" do expect do described_class.run("non_existent_executable") end.not_to raise_error end it 'does not format `stderr` when it starts with \r' do expect do Class.new.extend(SystemCommand::Mixin).system_command \ "bash", args: [ "-c", 'printf "\r%s" "################### 27.6%" 1>&2', ] end.to output( "\r################### 27.6%", ).to_stderr end context "when given an executable with spaces and no arguments" do let(:executable) { mktmpdir/"App Uninstaller" } before do executable.write <<~SH #!/usr/bin/env bash true SH FileUtils.chmod "+x", executable end it "does not interpret the executable as a shell line" do expect(Class.new.extend(SystemCommand::Mixin).system_command(executable)).to be_a_success end end context "when given arguments with secrets" do it "does not leak the secrets" do redacted_msg = /#{Regexp.escape("username:******")}/ expect do described_class.run! "curl", args: %w[--user username:hunter2], verbose: true, debug: true, secrets: %w[hunter2] end.to raise_error(ErrorDuringExecution, redacted_msg).and output(redacted_msg).to_stderr end it "does not leak the secrets set by environment" do redacted_msg = /#{Regexp.escape("username:******")}/ expect do ENV["PASSWORD"] = "hunter2" described_class.run! "curl", args: %w[--user username:hunter2], debug: true, verbose: true end.to raise_error(ErrorDuringExecution, redacted_msg).and output(redacted_msg).to_stderr end end context "when running a process that prints secrets" do it "does not leak the secrets" do redacted_msg = /#{Regexp.escape("username:******")}/ expect do described_class.run! "echo", args: %w[username:hunter2], verbose: true, print_stdout: true, secrets: %w[hunter2] end.to output(redacted_msg).to_stdout end it "does not leak the secrets set by environment" do redacted_msg = /#{Regexp.escape("username:******")}/ expect do ENV["PASSWORD"] = "hunter2" described_class.run! "echo", args: %w[username:hunter2], print_stdout: true, verbose: true end.to output(redacted_msg).to_stdout end end context "when a `SIGINT` handler is set in the parent process" do it "is not interrupted" do start_time = Time.now pid = fork do trap("INT") do # Ignore SIGINT. end described_class.run! "sleep", args: [5] exit! end sleep 1 Process.kill("INT", pid) Process.waitpid(pid) expect(Time.now - start_time).to be >= 5 end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/head_software_spec_spec.rb
Library/Homebrew/test/head_software_spec_spec.rb
# frozen_string_literal: true require "head_software_spec" RSpec.describe HeadSoftwareSpec do subject(:head_spec) { described_class.new } specify "#version" do expect(head_spec.version).to eq(Version.new("HEAD")) end specify "#verify_download_integrity" do expect(head_spec.verify_download_integrity(Pathname.new("head.zip"))).to be_nil end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/compiler_failure_spec.rb
Library/Homebrew/test/compiler_failure_spec.rb
# frozen_string_literal: true require "compilers" RSpec.describe CompilerFailure do alias_matcher :fail_with, :be_fails_with describe "::create" do it "creates a failure when given a symbol" do failure = described_class.create(:clang) expect(failure).to fail_with( instance_double(CompilerSelector::Compiler, "Compiler", type: :clang, name: :clang, version: 600), ) end it "can be given a build number in a block" do failure = described_class.create(:clang) { build 700 } expect(failure).to fail_with( instance_double(CompilerSelector::Compiler, "Compiler", type: :clang, name: :clang, version: 700), ) end it "can be given an empty block" do failure = described_class.create(:clang) do # do nothing end expect(failure).to fail_with( instance_double(CompilerSelector::Compiler, "Compiler", type: :clang, name: :clang, version: 600), ) end it "creates a failure when given a hash" do failure = described_class.create(gcc: "7") expect(failure).to fail_with( instance_double(CompilerSelector::Compiler, "Compiler", type: :gcc, name: "gcc-7", version: Version.new("7")), ) expect(failure).to fail_with( instance_double( CompilerSelector::Compiler, "Compiler", type: :gcc, name: "gcc-7", version: Version.new("7.1") ), ) expect(failure).not_to fail_with( instance_double( CompilerSelector::Compiler, "Compiler", type: :gcc, name: "gcc-6", version: Version.new("6.0") ), ) end it "creates a failure when given a hash and a block with aversion" do failure = described_class.create(gcc: "7") { version "7.1" } expect(failure).to fail_with( instance_double(CompilerSelector::Compiler, "Compiler", type: :gcc, name: "gcc-7", version: Version.new("7")), ) expect(failure).to fail_with( instance_double( CompilerSelector::Compiler, "Compiler", type: :gcc, name: "gcc-7", version: Version.new("7.1") ), ) expect(failure).not_to fail_with( instance_double( CompilerSelector::Compiler, "Compiler", type: :gcc, name: "gcc-7", version: Version.new("7.2") ), ) end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/keg_spec.rb
Library/Homebrew/test/keg_spec.rb
# frozen_string_literal: true require "keg" require "stringio" RSpec.describe Keg do include FileUtils def setup_test_keg(name, version) path = HOMEBREW_CELLAR/name/version (path/"bin").mkpath %w[hiworld helloworld goodbye_cruel_world].each do |file| touch path/"bin"/file end keg = described_class.new(path) kegs << keg keg end let(:dst) { HOMEBREW_PREFIX/"bin"/"helloworld" } let(:nonexistent) { Pathname.new("/some/nonexistent/path") } let!(:keg) { setup_test_keg("foo", "1.0") } let(:kegs) { [] } before do (HOMEBREW_PREFIX/"bin").mkpath (HOMEBREW_PREFIX/"lib").mkpath end after do kegs.each(&:unlink) rmtree HOMEBREW_PREFIX/"lib" end specify "::all" do expect(described_class.all).to eq([keg]) end specify "#empty_installation?" do %w[.DS_Store INSTALL_RECEIPT.json LICENSE.txt].each do |file| touch keg/file end expect(keg).to exist expect(keg).to be_a_directory expect(keg).not_to be_an_empty_installation FileUtils.rm_r(keg/"bin") expect(keg).to be_an_empty_installation (keg/"bin").mkpath touch keg.join("bin", "todo") expect(keg).not_to be_an_empty_installation end specify "#oldname_opt_records" do expect(keg.oldname_opt_records).to be_empty oldname_opt_record = HOMEBREW_PREFIX/"opt/oldfoo" oldname_opt_record.make_relative_symlink(HOMEBREW_CELLAR/"foo/1.0") expect(keg.oldname_opt_records).to eq([oldname_opt_record]) end specify "#remove_oldname_opt_records" do oldname_opt_record = HOMEBREW_PREFIX/"opt/oldfoo" oldname_opt_record.make_relative_symlink(HOMEBREW_CELLAR/"foo/2.0") keg.remove_oldname_opt_records expect(oldname_opt_record).to be_a_symlink oldname_opt_record.unlink oldname_opt_record.make_relative_symlink(HOMEBREW_CELLAR/"foo/1.0") keg.remove_oldname_opt_records expect(oldname_opt_record).not_to be_a_symlink end describe "#link" do it "links a Keg" do expect(keg.link).to eq(3) (HOMEBREW_PREFIX/"bin").children.each do |c| expect(c.readlink).to be_relative end end context "with dry run set to true" do let(:options) { { dry_run: true } } it "only prints what would be done" do expect do expect(keg.link(**options)).to eq(0) end.to output(<<~EOF).to_stdout #{HOMEBREW_PREFIX}/bin/goodbye_cruel_world #{HOMEBREW_PREFIX}/bin/helloworld #{HOMEBREW_PREFIX}/bin/hiworld EOF expect(keg).not_to be_linked end end it "fails when already linked" do keg.link expect { keg.link }.to raise_error(Keg::AlreadyLinkedError) end it "fails when files exist" do touch dst expect { keg.link }.to raise_error(Keg::ConflictError) end it "ignores broken symlinks at target" do src = keg/"bin"/"helloworld" dst.make_symlink(nonexistent) keg.link expect(dst.readlink).to eq(src.relative_path_from(dst.dirname)) end context "with overwrite set to true" do let(:options) { { overwrite: true } } it "overwrite existing files" do touch dst expect(keg.link(**options)).to eq(3) expect(keg).to be_linked end it "overwrites broken symlinks" do dst.make_symlink "nowhere" expect(keg.link(**options)).to eq(3) expect(keg).to be_linked end it "still supports dryrun" do touch dst options[:dry_run] = true expect do expect(keg.link(**options)).to eq(0) end.to output(<<~EOF).to_stdout #{dst} EOF expect(keg).not_to be_linked end end it "also creates an opt link" do expect(keg).not_to be_optlinked keg.link expect(keg).to be_optlinked end specify "pkgconfig directory is created" do link = HOMEBREW_PREFIX/"lib"/"pkgconfig" (keg/"lib"/"pkgconfig").mkpath keg.link expect(link.lstat).to be_a_directory end specify "cmake directory is created" do link = HOMEBREW_PREFIX/"lib"/"cmake" (keg/"lib"/"cmake").mkpath keg.link expect(link.lstat).to be_a_directory end specify "symlinks are linked directly" do link = HOMEBREW_PREFIX/"lib"/"pkgconfig" (keg/"lib"/"example").mkpath (keg/"lib"/"pkgconfig").make_symlink "example" keg.link expect(link.resolved_path).to be_a_symlink expect(link.lstat).to be_a_symlink end end describe "#unlink" do it "unlinks a Keg" do keg.link expect(dst).to be_a_symlink expect(keg.unlink).to eq(3) expect(dst).not_to be_a_symlink end it "prunes empty top-level directories" do mkpath HOMEBREW_PREFIX/"lib/foo/bar" mkpath keg/"lib/foo/bar" touch keg/"lib/foo/bar/file1" keg.unlink expect(HOMEBREW_PREFIX/"lib/foo").not_to be_a_directory end it "ignores .DS_Store when pruning empty directories" do mkpath HOMEBREW_PREFIX/"lib/foo/bar" touch HOMEBREW_PREFIX/"lib/foo/.DS_Store" mkpath keg/"lib/foo/bar" touch keg/"lib/foo/bar/file1" keg.unlink expect(HOMEBREW_PREFIX/"lib/foo").not_to be_a_directory expect(HOMEBREW_PREFIX/"lib/foo/.DS_Store").not_to exist end it "doesn't remove opt link" do keg.link keg.unlink expect(keg).to be_optlinked end it "preverves broken symlinks pointing outside the Keg" do keg.link dst.delete dst.make_symlink(nonexistent) keg.unlink expect(dst).to be_a_symlink end it "preverves broken symlinks pointing into the Keg" do keg.link dst.resolved_path.delete keg.unlink expect(dst).to be_a_symlink end it "preverves symlinks pointing outside the Keg" do keg.link dst.delete dst.make_symlink(Pathname.new("/bin/sh")) keg.unlink expect(dst).to be_a_symlink end it "preserves real files" do keg.link dst.delete touch dst keg.unlink expect(dst).to be_a_file end it "ignores nonexistent file" do keg.link dst.delete expect(keg.unlink).to eq(2) end it "doesn't remove links to symlinks" do a = HOMEBREW_CELLAR/"a"/"1.0" b = HOMEBREW_CELLAR/"b"/"1.0" (a/"lib"/"example").mkpath (a/"lib"/"example2").make_symlink "example" (b/"lib"/"example2").mkpath a = described_class.new(a) b = described_class.new(b) a.link lib = HOMEBREW_PREFIX/"lib" expect(lib.children.length).to eq(2) expect { b.link }.to raise_error(Keg::ConflictError) expect(lib.children.length).to eq(2) end # This is a legacy violation that would benefit from a clear expectation. # rubocop:disable RSpec/NoExpectationExample it "removes broken symlinks that conflict with directories" do a = HOMEBREW_CELLAR/"a"/"1.0" (a/"lib"/"foo").mkpath keg = described_class.new(a) link = HOMEBREW_PREFIX/"lib"/"foo" link.parent.mkpath link.make_symlink(nonexistent) keg.link end # rubocop:enable RSpec/NoExpectationExample end describe "#optlink" do it "creates an opt link" do oldname_opt_record = HOMEBREW_PREFIX/"opt/oldfoo" oldname_opt_record.make_relative_symlink(HOMEBREW_CELLAR/"foo/1.0") keg_record = HOMEBREW_CELLAR/"foo"/"2.0" (keg_record/"bin").mkpath keg = described_class.new(keg_record) keg.optlink expect(keg_record).to eq(oldname_opt_record.resolved_path) keg.uninstall expect(oldname_opt_record).not_to be_a_symlink end it "doesn't fail if already opt-linked" do keg.opt_record.make_relative_symlink Pathname.new(keg) keg.optlink expect(keg).to be_optlinked end it "replaces an existing directory" do keg.opt_record.mkpath keg.optlink expect(keg).to be_optlinked end it "replaces an existing file" do keg.opt_record.parent.mkpath keg.opt_record.write("foo") keg.optlink expect(keg).to be_optlinked end end describe "#homebrew_created_file?" do it "identifies Homebrew service files" do plist_file = instance_double(Pathname, extname: ".plist", basename: Pathname.new("homebrew.foo.plist")) service_file = instance_double(Pathname, extname: ".service", basename: Pathname.new("homebrew.foo.service")) timer_file = instance_double(Pathname, extname: ".timer", basename: Pathname.new("homebrew.foo.timer")) regular_file = instance_double(Pathname, extname: ".txt", basename: Pathname.new("readme.txt")) non_homebrew_plist = instance_double(Pathname, extname: ".plist", basename: Pathname.new("com.example.foo.plist")) allow(plist_file.basename).to receive(:to_s).and_return("homebrew.foo.plist") allow(service_file.basename).to receive(:to_s).and_return("homebrew.foo.service") allow(timer_file.basename).to receive(:to_s).and_return("homebrew.foo.timer") allow(regular_file.basename).to receive(:to_s).and_return("readme.txt") allow(non_homebrew_plist.basename).to receive(:to_s).and_return("com.example.foo.plist") expect(keg.homebrew_created_file?(plist_file)).to be true expect(keg.homebrew_created_file?(service_file)).to be true expect(keg.homebrew_created_file?(timer_file)).to be true expect(keg.homebrew_created_file?(regular_file)).to be false expect(keg.homebrew_created_file?(non_homebrew_plist)).to be false end end specify "#link and #unlink" do expect(keg).not_to be_linked keg.link expect(keg).to be_linked keg.unlink expect(keg).not_to be_linked end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/dependable_spec.rb
Library/Homebrew/test/dependable_spec.rb
# frozen_string_literal: true require "dependable" RSpec.describe Dependable do alias_matcher :be_a_build_dependency, :be_build subject(:dependable) do Class.new do include Dependable def initialize @tags = ["foo", "bar", :build] end end.new end specify "#options" do expect(dependable.options.as_flags.sort).to eq(%w[--foo --bar].sort) end specify "#build?" do # rubocop:todo RSpec/AggregateExamples expect(dependable).to be_a_build_dependency end specify "#optional?" do # rubocop:todo RSpec/AggregateExamples expect(dependable).not_to be_optional end specify "#recommended?" do # rubocop:todo RSpec/AggregateExamples expect(dependable).not_to be_recommended end specify "#no_linkage?" do # rubocop:todo RSpec/AggregateExamples expect(dependable).not_to be_no_linkage end describe "with no_linkage tag" do subject(:dependable_no_linkage) do Class.new do include Dependable def initialize @tags = [:no_linkage] end end.new end specify "#no_linkage?" do expect(dependable_no_linkage).to be_no_linkage end specify "#required?" do # rubocop:todo RSpec/AggregateExamples expect(dependable_no_linkage).to be_required end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false