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/bundle/commands/cleanup.rb
Library/Homebrew/bundle/commands/cleanup.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "utils/formatter" module Homebrew module Bundle module Commands # TODO: refactor into multiple modules module Cleanup def self.reset! require "bundle/cask_dumper" require "bundle/formula_dumper" require "bundle/tap_dumper" require "bundle/vscode_extension_dumper" require "bundle/flatpak_dumper" require "bundle/brew_services" @dsl = nil @kept_casks = nil @kept_formulae = nil Homebrew::Bundle::CaskDumper.reset! Homebrew::Bundle::FormulaDumper.reset! Homebrew::Bundle::TapDumper.reset! Homebrew::Bundle::VscodeExtensionDumper.reset! Homebrew::Bundle::FlatpakDumper.reset! Homebrew::Bundle::BrewServices.reset! end def self.run(global: false, file: nil, force: false, zap: false, dsl: nil, formulae: true, casks: true, taps: true, vscode: true, flatpak: true) @dsl ||= dsl casks = casks ? casks_to_uninstall(global:, file:) : [] formulae = formulae ? formulae_to_uninstall(global:, file:) : [] taps = taps ? taps_to_untap(global:, file:) : [] vscode_extensions = vscode ? vscode_extensions_to_uninstall(global:, file:) : [] flatpaks = flatpak ? flatpaks_to_uninstall(global:, file:) : [] if force if casks.any? args = zap ? ["--zap"] : [] Kernel.system HOMEBREW_BREW_FILE, "uninstall", "--cask", *args, "--force", *casks puts "Uninstalled #{casks.size} cask#{"s" if casks.size != 1}" end if formulae.any? # Mark Brewfile formulae as installed_on_request to prevent autoremove # from removing them when their dependents are uninstalled require "bundle/brewfile" @dsl ||= Brewfile.read(global:, file:) Homebrew::Bundle.mark_as_installed_on_request!(@dsl.entries) Kernel.system HOMEBREW_BREW_FILE, "uninstall", "--formula", "--force", *formulae puts "Uninstalled #{formulae.size} formula#{"e" if formulae.size != 1}" end Kernel.system HOMEBREW_BREW_FILE, "untap", *taps if taps.any? Bundle.exchange_uid_if_needed! do vscode_extensions.each do |extension| Kernel.system(T.must(Bundle.which_vscode).to_s, "--uninstall-extension", extension) end end if flatpaks.any? flatpaks.each do |flatpak_name| Kernel.system "flatpak", "uninstall", "-y", "--system", flatpak_name end puts "Uninstalled #{flatpaks.size} flatpak#{"s" if flatpaks.size != 1}" end cleanup = system_output_no_stderr(HOMEBREW_BREW_FILE, "cleanup") puts cleanup unless cleanup.empty? else would_uninstall = false if casks.any? puts "Would uninstall casks:" puts Formatter.columns casks would_uninstall = true end if formulae.any? puts "Would uninstall formulae:" puts Formatter.columns formulae would_uninstall = true end if taps.any? puts "Would untap:" puts Formatter.columns taps would_uninstall = true end if vscode_extensions.any? puts "Would uninstall VSCode extensions:" puts Formatter.columns vscode_extensions would_uninstall = true end if flatpaks.any? puts "Would uninstall flatpaks:" puts Formatter.columns flatpaks would_uninstall = true end cleanup = system_output_no_stderr(HOMEBREW_BREW_FILE, "cleanup", "--dry-run") unless cleanup.empty? puts "Would `brew cleanup`:" puts cleanup end puts "Run `brew bundle cleanup --force` to make these changes." if would_uninstall || !cleanup.empty? exit 1 if would_uninstall end end def self.casks_to_uninstall(global: false, file: nil) require "bundle/cask_dumper" Homebrew::Bundle::CaskDumper.cask_names - kept_casks(global:, file:) end def self.formulae_to_uninstall(global: false, file: nil) kept_formulae = self.kept_formulae(global:, file:) require "bundle/formula_dumper" require "bundle/formula_installer" current_formulae = Homebrew::Bundle::FormulaDumper.formulae current_formulae.reject! do |f| Homebrew::Bundle::FormulaInstaller.formula_in_array?(f[:full_name], kept_formulae) end # Don't try to uninstall formulae with keepme references current_formulae.reject! do |f| Formula[f[:full_name]].installed_kegs.any? do |keg| keg.keepme_refs.present? end end current_formulae.map { |f| f[:full_name] } end private_class_method def self.kept_formulae(global: false, file: nil) require "bundle/brewfile" require "bundle/formula_dumper" require "bundle/cask_dumper" @kept_formulae ||= begin @dsl ||= Brewfile.read(global:, file:) kept_formulae = @dsl.entries.select { |e| e.type == :brew }.map(&:name) kept_formulae += Homebrew::Bundle::CaskDumper.formula_dependencies(kept_casks) kept_formulae.map! do |f| Homebrew::Bundle::FormulaDumper.formula_aliases.fetch( f, Homebrew::Bundle::FormulaDumper.formula_oldnames.fetch(f, f), ) end kept_formulae + recursive_dependencies(Homebrew::Bundle::FormulaDumper.formulae, kept_formulae) end end private_class_method def self.kept_casks(global: false, file: nil) require "bundle/brewfile" return @kept_casks if @kept_casks @dsl ||= Brewfile.read(global:, file:) kept_casks = @dsl.entries.select { |e| e.type == :cask }.flat_map(&:name) kept_casks.map! do |c| Homebrew::Bundle::CaskDumper.cask_oldnames.fetch(c, c) end @kept_casks = kept_casks end private_class_method def self.recursive_dependencies(current_formulae, formulae_names, top_level: true) @checked_formulae_names = [] if top_level dependencies = T.let([], T::Array[Formula]) formulae_names.each do |name| next if @checked_formulae_names.include?(name) formula = current_formulae.find { |f| f[:full_name] == name } next unless formula f_deps = formula[:dependencies] unless formula[:poured_from_bottle?] f_deps += formula[:build_dependencies] f_deps.uniq! end next unless f_deps next if f_deps.empty? @checked_formulae_names << name f_deps += recursive_dependencies(current_formulae, f_deps, top_level: false) dependencies += f_deps end dependencies.uniq end IGNORED_TAPS = %w[homebrew/core].freeze def self.taps_to_untap(global: false, file: nil) require "bundle/brewfile" require "bundle/tap_dumper" @dsl ||= Brewfile.read(global:, file:) kept_formulae = self.kept_formulae(global:, file:).filter_map { lookup_formula(it) } kept_taps = @dsl.entries.select { |e| e.type == :tap }.map(&:name) kept_taps += kept_formulae.filter_map(&:tap).map(&:name) current_taps = Homebrew::Bundle::TapDumper.tap_names current_taps - kept_taps - IGNORED_TAPS end def self.lookup_formula(formula) Formulary.factory(formula) rescue TapFormulaUnavailableError # ignore these as an unavailable formula implies there is no tap to worry about nil end def self.vscode_extensions_to_uninstall(global: false, file: nil) require "bundle/brewfile" @dsl ||= Brewfile.read(global:, file:) kept_extensions = @dsl.entries.select { |e| e.type == :vscode }.map { |x| x.name.downcase } # To provide a graceful migration from `Brewfile`s that don't yet or # don't want to use `vscode`: don't remove any extensions if we don't # find any in the `Brewfile`. return [].freeze if kept_extensions.empty? require "bundle/vscode_extension_dumper" current_extensions = Homebrew::Bundle::VscodeExtensionDumper.extensions current_extensions - kept_extensions end def self.flatpaks_to_uninstall(global: false, file: nil) return [].freeze unless Bundle.flatpak_installed? require "bundle/brewfile" @dsl ||= Brewfile.read(global:, file:) kept_flatpaks = @dsl.entries.select { |e| e.type == :flatpak }.map(&:name) # To provide a graceful migration from `Brewfile`s that don't yet or # don't want to use `flatpak`: don't remove any flatpaks if we don't # find any in the `Brewfile`. return [].freeze if kept_flatpaks.empty? require "bundle/flatpak_dumper" current_flatpaks = Homebrew::Bundle::FlatpakDumper.packages current_flatpaks - kept_flatpaks end def self.system_output_no_stderr(cmd, *args) IO.popen([cmd, *args], err: :close).read 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/bundle/commands/exec.rb
Library/Homebrew/bundle/commands/exec.rb
# typed: true # frozen_string_literal: true require "English" require "exceptions" require "extend/ENV" require "utils" require "PATH" require "utils/output" module Homebrew module Bundle module Commands module Exec extend Utils::Output::Mixin PATH_LIKE_ENV_REGEX = /.+#{File::PATH_SEPARATOR}/ sig { params( args: String, global: T::Boolean, file: T.nilable(String), subcommand: String, services: T::Boolean, check: T::Boolean, no_secrets: T::Boolean, ).void } def self.run( *args, global: false, file: nil, subcommand: "", services: false, check: false, no_secrets: false ) if check require "bundle/commands/check" Homebrew::Bundle::Commands::Check.run(global:, file:, quiet: true) end # Store the old environment so we can check if things were already set # before we start mutating it. old_env = ENV.to_h ENV.clear_sensitive_environment! if no_secrets # Setup Homebrew's ENV extensions ENV.activate_extensions! command = args.first raise UsageError, "No command to execute was specified!" if command.blank? require "bundle/brewfile" @dsl = Brewfile.read(global:, file:) require "formula" require "formulary" ENV.deps = @dsl.entries.filter_map do |entry| next if entry.type != :brew Formulary.factory(entry.name) end # Allow setting all dependencies to be keg-only # (i.e. should be explicitly in HOMEBREW_*PATHs ahead of HOMEBREW_PREFIX) ENV.keg_only_deps = if ENV["HOMEBREW_BUNDLE_EXEC_ALL_KEG_ONLY_DEPS"].present? ENV.delete("HOMEBREW_BUNDLE_EXEC_ALL_KEG_ONLY_DEPS") ENV.deps else ENV.deps.select(&:keg_only?) end ENV.setup_build_environment # Enable compiler flag filtering ENV.refurbish_args # Set up `nodenv`, `pyenv` and `rbenv` if present. env_formulae = %w[nodenv pyenv rbenv] ENV.deps.each do |dep| dep_name = dep.name next unless env_formulae.include?(dep_name) dep_root = ENV.fetch("HOMEBREW_#{dep_name.upcase}_ROOT", "#{Dir.home}/.#{dep_name}") ENV.prepend_path "PATH", Pathname.new(dep_root)/"shims" end # Setup pkgconf, if needed, to help locate packages Bundle.prepend_pkgconf_path_if_needed! # For commands which aren't either absolute or relative # Add the command directory to PATH, since it may get blown away by superenv if command.exclude?("/") && (which_command = which(command)).present? ENV.prepend_path "PATH", which_command.dirname.to_s end # Replace the formula versions from the environment variables ENV.deps.each do |formula| formula_name = formula.name formula_version = Bundle.formula_versions_from_env(formula_name) next unless formula_version ENV.each do |key, value| opt = %r{/opt/#{formula_name}([/:$])} next unless value.match(opt) cellar = "/Cellar/#{formula_name}/#{formula_version}\\1" # Look for PATH-like environment variables ENV[key] = if key.include?("PATH") && value.match?(PATH_LIKE_ENV_REGEX) rejected_opts = [] path = PATH.new(ENV.fetch("PATH")) .reject do |path_value| rejected_opts << path_value if path_value.match?(opt) end rejected_opts.each do |path_value| path.prepend(path_value.gsub(opt, cellar)) end path.to_s else value.gsub(opt, cellar) end end end # Ensure brew bundle exec/sh/env commands have access to other tools in the PATH if (homebrew_path = ENV.fetch("HOMEBREW_PATH", nil)) ENV.append_path "PATH", homebrew_path end # For commands which aren't either absolute or relative raise "command was not found in your PATH: #{command}" if command.exclude?("/") && which(command).nil? %w[HOMEBREW_TEMP TMPDIR HOMEBREW_TMPDIR].each do |var| value = ENV.fetch(var, nil) next if value.blank? next if File.writable?(value) ENV.delete(var) end ENV.each do |key, value| # Look for PATH-like environment variables next if key.exclude?("PATH") || !value.match?(PATH_LIKE_ENV_REGEX) # Exclude Homebrew shims from the PATH as they don't work # without all Homebrew environment variables and can interfere with # non-Homebrew builds. ENV[key] = PATH.new(value) .reject do |path_value| path_value.include?("/Homebrew/shims/") end.to_s end if subcommand == "env" ENV.sort.each do |key, value| # Skip exporting Homebrew internal variables that won't be used by other tools. # Those Homebrew needs have already been set to global constants and/or are exported again later. # Setting these globally can interfere with nested Homebrew invocations/environments. if key.start_with?("HOMEBREW_", "PORTABLE_RUBY_") ENV.delete(key) next end # No need to export empty values. next if value.blank? # Skip exporting things that were the same in the old environment. old_value = old_env[key] next if old_value == value # Look for PATH-like environment variables if key.include?("PATH") && value.match?(PATH_LIKE_ENV_REGEX) old_values = old_value.to_s.split(File::PATH_SEPARATOR) path = PATH.new(value) .reject do |path_value| # Exclude existing/old values as they've already been exported. old_values.include?(path_value) end next if path.blank? puts "export #{key}=\"#{Utils::Shell.sh_quote(path.to_s)}:${#{key}:-}\"" else puts "export #{key}=\"#{Utils::Shell.sh_quote(value)}\"" end end return elsif subcommand == "sh" preferred_path = Utils::Shell.preferred_path(default: "/bin/bash") notice = unless Homebrew::EnvConfig.no_env_hints? <<~EOS Your shell has been configured to use a build environment from your `Brewfile`. This should help you build stuff. Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`). When done, type `exit`. EOS end ENV["HOMEBREW_FORCE_API_AUTO_UPDATE"] = nil args = [Utils::Shell.shell_with_prompt("brew bundle", preferred_path:, notice:)] end if services require "bundle/brew_services" exit_code = T.let(0, Integer) run_services(@dsl.entries) do Kernel.system(*args) if (system_exit_code = $CHILD_STATUS&.exitstatus) exit_code = system_exit_code end end exit!(exit_code) else exec(*args) end end sig { params( entries: T::Array[Homebrew::Bundle::Dsl::Entry], _block: T.proc.params( entry: Homebrew::Bundle::Dsl::Entry, info: T::Hash[String, T.untyped], service_file: Pathname, conflicting_services: T::Array[T::Hash[String, T.anything]], ).void, ).void } private_class_method def self.map_service_info(entries, &_block) entries_formulae = entries.filter_map do |entry| next if entry.type != :brew formula = Formula[entry.name] next unless formula.any_version_installed? [entry, formula] end.to_h return if entries_formulae.empty? conflicts = entries_formulae.to_h do |entry, formula| [ entry, ( formula.versioned_formulae_names + formula.conflicts.map(&:name) + Array(entry.options[:conflicts_with]) ).uniq, ] end # The formula + everything that could possible conflict with the service names_to_query = entries_formulae.flat_map do |entry, formula| [ formula.name, *conflicts.fetch(entry), ] end # We parse from a command invocation so that brew wrappers can invoke special actions # for the elevated nature of `brew services` services_info = JSON.parse( Utils.safe_popen_read(HOMEBREW_BREW_FILE, "services", "info", "--json", *names_to_query), ) entries_formulae.filter_map do |entry, formula| service_file = Bundle::BrewServices.versioned_service_file(entry.name) unless service_file&.file? prefix = formula.any_installed_prefix next if prefix.nil? service_file = if Homebrew::Services::System.launchctl? prefix/"#{formula.plist_name}.plist" else prefix/"#{formula.service_name}.service" end end next unless service_file.file? info = services_info.find { |candidate| candidate["name"] == formula.name } conflicting_services = services_info.select do |candidate| next unless candidate["running"] conflicts.fetch(entry).include?(candidate["name"]) end raise "Failed to get service info for #{entry.name}" if info.nil? yield entry, info, service_file, conflicting_services end end sig { params(entries: T::Array[Homebrew::Bundle::Dsl::Entry], _block: T.nilable(T.proc.void)).void } private_class_method def self.run_services(entries, &_block) entries_to_stop = [] services_to_restart = [] map_service_info(entries) do |entry, info, service_file, conflicting_services| # Don't restart if already running this version loaded_file = Pathname.new(info["loaded_file"].to_s) next if info["running"] && loaded_file.file? && loaded_file.realpath == service_file.realpath if info["running"] && !Bundle::BrewServices.stop(info["name"], keep: true) opoo "Failed to stop #{info["name"]} service" end conflicting_services.each do |conflict| if Bundle::BrewServices.stop(conflict["name"], keep: true) services_to_restart << conflict["name"] if conflict["registered"] else opoo "Failed to stop #{conflict["name"]} service" end end unless Bundle::BrewServices.run(info["name"], file: service_file) opoo "Failed to start #{info["name"]} service" end entries_to_stop << entry end return unless block_given? begin yield ensure # Do a full re-evaluation of services instead state has changed stop_services(entries_to_stop) services_to_restart.each do |service| next if Bundle::BrewServices.run(service) opoo "Failed to restart #{service} service" end end end sig { params(entries: T::Array[Homebrew::Bundle::Dsl::Entry]).void } private_class_method def self.stop_services(entries) map_service_info(entries) do |_, info, _, _| next unless info["loaded"] # Try avoid services not started by `brew bundle services` next if Homebrew::Services::System.launchctl? && info["registered"] if info["running"] && !Bundle::BrewServices.stop(info["name"], keep: true) opoo "Failed to stop #{info["name"]} service" end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/commands/list.rb
Library/Homebrew/bundle/commands/list.rb
# typed: strict # frozen_string_literal: true require "bundle/brewfile" require "bundle/lister" module Homebrew module Bundle module Commands module List sig { params(global: T::Boolean, file: T.nilable(String), formulae: T::Boolean, casks: T::Boolean, taps: T::Boolean, mas: T::Boolean, vscode: T::Boolean, go: T::Boolean, cargo: T::Boolean, flatpak: T::Boolean).void } def self.run(global:, file:, formulae:, casks:, taps:, mas:, vscode:, go:, cargo:, flatpak:) parsed_entries = Brewfile.read(global:, file:).entries Homebrew::Bundle::Lister.list( parsed_entries, formulae:, casks:, taps:, mas:, vscode:, go:, cargo:, flatpak:, ) 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/bundle/commands/check.rb
Library/Homebrew/bundle/commands/check.rb
# typed: strict # frozen_string_literal: true require "bundle/checker" module Homebrew module Bundle module Commands module Check sig { params(global: T::Boolean, file: T.nilable(String), no_upgrade: T::Boolean, verbose: T::Boolean, quiet: T::Boolean).void } def self.run(global: false, file: nil, no_upgrade: false, verbose: false, quiet: false) output_errors = verbose exit_on_first_error = !verbose check_result = Homebrew::Bundle::Checker.check( global:, file:, exit_on_first_error:, no_upgrade:, verbose: ) # Allow callers of `brew bundle check` to specify when they've already # output some formulae errors. check_missing_formulae = ENV.fetch("HOMEBREW_BUNDLE_CHECK_ALREADY_OUTPUT_FORMULAE_ERRORS", "") .strip .split if check_result.work_to_be_done puts "brew bundle can't satisfy your Brewfile's dependencies." if check_missing_formulae.blank? if output_errors check_result.errors.each do |error| if (match = error.match(/^Formula (.+) needs to be installed/)) && check_missing_formulae.include?(match[1]) next end puts "→ #{error}" end end puts "Satisfy missing dependencies with `brew bundle install`." exit 1 end puts "The Brewfile's dependencies are satisfied." unless quiet 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/bundle/commands/install.rb
Library/Homebrew/bundle/commands/install.rb
# typed: strict # frozen_string_literal: true require "bundle/brewfile" require "bundle/installer" module Homebrew module Bundle module Commands module Install sig { params( global: T::Boolean, file: T.nilable(String), no_lock: T::Boolean, no_upgrade: T::Boolean, verbose: T::Boolean, force: T::Boolean, quiet: T::Boolean, ).void } def self.run(global: false, file: nil, no_lock: false, no_upgrade: false, verbose: false, force: false, quiet: false) @dsl = Brewfile.read(global:, file:) result = Homebrew::Bundle::Installer.install!( @dsl.entries, global:, file:, no_lock:, no_upgrade:, verbose:, force:, quiet:, ) # Mark Brewfile formulae as installed_on_request to prevent autoremove # from removing them when their dependents are uninstalled Homebrew::Bundle.mark_as_installed_on_request!(@dsl.entries) result || exit(1) end sig { returns(T.nilable(Dsl)) } def self.dsl @dsl ||= T.let(nil, T.nilable(Dsl)) @dsl 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/bundle/commands/remove.rb
Library/Homebrew/bundle/commands/remove.rb
# typed: strict # frozen_string_literal: true require "bundle/remover" module Homebrew module Bundle module Commands module Remove sig { params(args: String, type: Symbol, global: T::Boolean, file: T.nilable(String)).void } def self.run(*args, type:, global:, file:) Homebrew::Bundle::Remover.remove(*args, type:, global:, file:) end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/disable_comment.rb
Library/Homebrew/rubocops/disable_comment.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop # Checks if rubocop disable comments have a clarifying comment preceding them. class DisableComment < Base MSG = "Add a clarifying comment to the RuboCop disable comment" sig { void } def on_new_investigation super processed_source.comments.each do |comment| next unless disable_comment?(comment) next if comment?(processed_source[comment.loc.line - 2]) add_offense(comment) end end private sig { params(comment: Parser::Source::Comment).returns(T::Boolean) } def disable_comment?(comment) comment.text.start_with? "# rubocop:disable" end sig { params(line: String).returns(T::Boolean) } def comment?(line) line.strip.start_with?("#") && line.strip.delete_prefix("#") != "" 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/rubocops/lines.rb
Library/Homebrew/rubocops/lines.rb
# typed: strict # frozen_string_literal: true require "macos_version" require "rubocops/extend/formula_cop" require "rubocops/shared/on_system_conditionals_helper" module RuboCop module Cop module FormulaAudit # This cop checks for various miscellaneous Homebrew coding styles. class Lines < FormulaCop sig { override.params(_formula_nodes: FormulaNodes).void } def audit_formula(_formula_nodes) [:automake, :ant, :autoconf, :emacs, :expat, :libtool, :mysql, :perl, :postgresql, :python, :python3, :rbenv, :ruby].each do |dependency| next unless depends_on?(dependency) problem ":#{dependency} is deprecated. Usage should be \"#{dependency}\"." end { apr: "apr-util", fortran: "gcc", gpg: "gnupg", hg: "mercurial", mpi: "open-mpi", python2: "python" }.each do |requirement, dependency| next unless depends_on?(requirement) problem ":#{requirement} is deprecated. Usage should be \"#{dependency}\"." end problem ":tex is deprecated." if depends_on?(:tex) end end # This cop makes sure that a space is used for class inheritance. class ClassInheritance < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) parent_class_node = formula_nodes.parent_class_node begin_pos = start_column(parent_class_node) end_pos = end_column(formula_nodes.class_node) return if begin_pos-end_pos == 3 problem "Use a space in class inheritance: " \ "class #{T.must(@formula_name).capitalize} < #{class_name(parent_class_node)}" end end # This cop makes sure that template comments are removed. class Comments < FormulaCop sig { override.params(_formula_nodes: FormulaNodes).void } def audit_formula(_formula_nodes) audit_comments do |comment| [ "# PLEASE REMOVE", "# Documentation:", "# if this fails, try separate make/make install steps", "# The URL of the archive", "## Naming --", "# if your formula fails when building in parallel", "# Remove unrecognized options if warned by configure", '# system "cmake', ].each do |template_comment| next unless comment.include?(template_comment) problem "Please remove default template comments" break end end audit_comments do |comment| # Commented-out depends_on next unless comment =~ /#\s*depends_on\s+(.+)\s*$/ problem "Commented-out dependency #{Regexp.last_match(1)}" end return if formula_tap != "homebrew-core" # Citation and tag comments from third-party taps audit_comments do |comment| next if comment !~ /#\s*(cite(?=\s*\w+:)|doi(?=\s*['"])|tag(?=\s*['"]))/ problem "Formulae in homebrew/core should not use `#{Regexp.last_match(1)}` comments" end end end # This cop makes sure that idiomatic `assert_*` statements are used. class AssertStatements < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? find_every_method_call_by_name(body_node, :assert).each do |method| if method_called_ever?(method, :include?) && !method_called_ever?(method, :!) problem "Use `assert_match` instead of `assert ...include?`" end if method_called_ever?(method, :exist?) && !method_called_ever?(method, :!) problem "Use `assert_path_exists <path_to_file>` instead of `#{method.source}`" end if method_called_ever?(method, :exist?) && method_called_ever?(method, :!) problem "Use `refute_path_exists <path_to_file>` instead of `#{method.source}`" end if method_called_ever?(method, :executable?) && !method_called_ever?(method, :!) problem "Use `assert_predicate <path_to_file>, :executable?` instead of `#{method.source}`" end end find_every_method_call_by_name(body_node, :assert_predicate).each do |method| args = parameters(method) next if args[1].source != ":exist?" offending_node(method) problem "Use `assert_path_exists <path_to_file>` instead of `#{method.source}`" do |corrector| correct = "assert_path_exists #{args.first.source}" correct += ", #{args[2].source}" if args.length == 3 corrector.replace(T.must(@offensive_node).source_range, correct) end end find_every_method_call_by_name(body_node, :refute_predicate).each do |method| args = parameters(method) next if args[1].source != ":exist?" offending_node(method) problem "Use `refute_path_exists <path_to_file>` instead of `#{method.source}`" do |corrector| correct = "refute_path_exists #{args.first.source}" correct += ", #{args[2].source}" if args.length == 3 corrector.replace(T.must(@offensive_node).source_range, correct) end end end end # This cop makes sure that `option`s are used idiomatically. class OptionDeclarations < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? problem "Use new-style option definitions" if find_method_def(body_node, :options) if formula_tap == "homebrew-core" # Use of build.with? implies options, which are forbidden in homebrew/core find_instance_method_call(body_node, :build, :without?) do problem "Formulae in homebrew/core should not use `build.without?`." end find_instance_method_call(body_node, :build, :with?) do problem "Formulae in homebrew/core should not use `build.with?`." end return end depends_on_build_with(body_node) do |build_with_node| offending_node(build_with_node) problem "Use `:optional` or `:recommended` instead of `if #{build_with_node.source}`" end find_instance_method_call(body_node, :build, :without?) do |method| next unless unless_modifier?(method.parent) correct = method.source.gsub("out?", "?") problem "Use `if #{correct}` instead of `unless #{method.source}`" end find_instance_method_call(body_node, :build, :with?) do |method| next unless unless_modifier?(method.parent) correct = method.source.gsub("?", "out?") problem "Use `if #{correct}` instead of `unless #{method.source}`" end find_instance_method_call(body_node, :build, :with?) do |method| next unless expression_negated?(method) problem "Instead of negating `build.with?`, use `build.without?`" end find_instance_method_call(body_node, :build, :without?) do |method| next unless expression_negated?(method) problem "Instead of negating `build.without?`, use `build.with?`" end find_instance_method_call(body_node, :build, :without?) do |method| arg = parameters(method).first next unless (match = regex_match_group(arg, /^-?-?without-(.*)/)) problem "Instead of duplicating `without`, " \ "use `build.without? \"#{match[1]}\"` to check for \"--without-#{match[1]}\"" end find_instance_method_call(body_node, :build, :with?) do |method| arg = parameters(method).first next unless (match = regex_match_group(arg, /^-?-?with-(.*)/)) problem "Instead of duplicating `with`, " \ "use `build.with? \"#{match[1]}\"` to check for '--with-#{match[1]}'" end find_instance_method_call(body_node, :build, :include?) do problem "`build.include?` is deprecated" end end sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def unless_modifier?(node) return false unless node.if_type? node = T.cast(node, RuboCop::AST::IfNode) node.modifier_form? && node.unless? end # Finds `depends_on "foo" if build.with?("bar")` or `depends_on "foo" if build.without?("bar")` def_node_search :depends_on_build_with, <<~EOS (if $(send (send nil? :build) {:with? :without?} str) (send nil? :depends_on str) nil?) EOS end # This cop makes sure that formulae depend on `open-mpi` instead of `mpich`. class MpiCheck < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? # Enforce use of OpenMPI for MPI dependency in core return if formula_tap != "homebrew-core" find_method_with_args(body_node, :depends_on, "mpich") do problem "Formulae in homebrew/core should use `depends_on \"open-mpi\"` " \ "instead of `#{T.must(@offensive_node).source}`." do |corrector| corrector.replace(T.must(@offensive_node).source_range, "depends_on \"open-mpi\"") end end end end # This cop makes sure that formulae use `std_npm_args` instead of older # `local_npm_install_args` and `std_npm_install_args`. class StdNpmArgs < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? find_method_with_args(body_node, :local_npm_install_args) do problem "Use `std_npm_args` instead of `#{T.cast(@offensive_node, RuboCop::AST::SendNode).method_name}`." do |corrector| corrector.replace(T.must(@offensive_node).source_range, "std_npm_args(prefix: false)") end end find_method_with_args(body_node, :std_npm_install_args) do |method| problem "Use `std_npm_args` instead of `#{T.cast(@offensive_node, RuboCop::AST::SendNode).method_name}`." do |corrector| if (param = parameters(method).first.source) == "libexec" corrector.replace(T.must(@offensive_node).source_range, "std_npm_args") else corrector.replace(T.must(@offensive_node).source_range, "std_npm_args(prefix: #{param})") end end end find_every_method_call_by_name(body_node, :system).each do |method| first_param, second_param = parameters(method) next if !node_equals?(first_param, "npm") || !node_equals?(second_param, "install") || method.source.match(/(std_npm_args|local_npm_install_args|std_npm_install_args)/) offending_node(method) problem "Use `std_npm_args` for npm install" end end end # This cop makes sure that formulae depend on `openssl` instead of `quictls`. class QuicTLSCheck < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? # Enforce use of OpenSSL for TLS dependency in core return if formula_tap != "homebrew-core" find_method_with_args(body_node, :depends_on, "quictls") do problem "Formulae in homebrew/core should use `depends_on \"openssl@3\"` " \ "instead of `#{T.must(@offensive_node).source}`." do |corrector| corrector.replace(T.must(@offensive_node).source_range, "depends_on \"openssl@3\"") end end end end # This cop makes sure that formulae do not depend on `pyoxidizer` at build-time # or run-time. class PyoxidizerCheck < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if formula_nodes.body_node.nil? # Disallow use of PyOxidizer as a dependency in core return if formula_tap != "homebrew-core" return unless depends_on?("pyoxidizer") problem "Formulae in homebrew/core should not use `#{T.must(@offensive_node).source}`." end end # This cop makes sure that the safe versions of `popen_*` calls are used. class SafePopenCommands < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? test = find_block(body_node, :test) [:popen_read, :popen_write].each do |unsafe_command| test_methods = [] unless test.nil? find_instance_method_call(test, "Utils", unsafe_command) do |method| test_methods << method.source_range end end find_instance_method_call(body_node, "Utils", unsafe_command) do |method| unless test_methods.include?(method.source_range) problem "Use `Utils.safe_#{unsafe_command}` instead of `Utils.#{unsafe_command}`" do |corrector| corrector.replace(T.must(@offensive_node).loc.selector, "safe_#{T.cast(@offensive_node, RuboCop::AST::SendNode).method_name}") end end end end end end # This cop makes sure that environment variables are passed correctly to `popen_*` calls. class ShellVariables < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? popen_commands = [ :popen, :popen_read, :safe_popen_read, :popen_write, :safe_popen_write, ] popen_commands.each do |command| find_instance_method_call(body_node, "Utils", command) do |method| next unless (match = regex_match_group(parameters(method).first, /^([^"' ]+)=([^"' ]+)(?: (.*))?$/)) good_args = "Utils.#{command}({ \"#{match[1]}\" => \"#{match[2]}\" }, \"#{match[3]}\")" problem "Use `#{good_args}` instead of `#{method.source}`" do |corrector| corrector.replace(method.source_range, good_args) end end end end end # This cop makes sure that `license` has the correct format. class LicenseArrays < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? license_node = find_node_method_by_name(body_node, :license) return unless license_node license = parameters(license_node).first return unless license.array_type? problem "Use `license any_of: #{license.source}` instead of `license #{license.source}`" do |corrector| corrector.replace(license_node.source_range, "license any_of: #{parameters(license_node).first.source}") end end end # This cop makes sure that nested `license` declarations are split onto multiple lines. class Licenses < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? license_node = find_node_method_by_name(body_node, :license) return unless license_node return if license_node.source.include?("\n") parameters(license_node).first.each_descendant(:hash).each do |license_hash| next if license_exception? license_hash problem "Split nested license declarations onto multiple lines" end end def_node_matcher :license_exception?, <<~EOS (hash (pair (sym :with) str)) EOS end # This cop makes sure that Python versions are consistent. class PythonVersions < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? python_formula_node = find_every_method_call_by_name(body_node, :depends_on).find do |dep| string_content(parameters(dep).first).start_with? "python@" end python_version = if python_formula_node.blank? other_python_nodes = find_every_method_call_by_name(body_node, :depends_on).select do |dep| parameters(dep).first.instance_of?(RuboCop::AST::HashNode) && string_content(parameters(dep).first.keys.first).start_with?("python@") end return if other_python_nodes.size != 1 string_content(parameters(other_python_nodes.first).first.keys.first).split("@").last else string_content(parameters(python_formula_node).first).split("@").last end find_strings(body_node).each do |str| content = string_content(str) next unless (match = content.match(/^python(@)?(\d\.\d+)$/)) next if python_version == match[2] fix = if match[1] "python@#{python_version}" else "python#{python_version}" end offending_node(str) problem "References to `#{content}` should " \ "match the specified python dependency (`#{fix}`)" do |corrector| corrector.replace(str.source_range, "\"#{fix}\"") end end end end # This cop makes sure that OS conditionals are consistent. class OnSystemConditionals < FormulaCop include OnSystemConditionalsHelper extend AutoCorrector NO_ON_SYSTEM_METHOD_NAMES = [:install, :post_install].freeze NO_ON_SYSTEM_BLOCK_NAMES = [:service, :test].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node NO_ON_SYSTEM_METHOD_NAMES.each do |formula_method_name| method_node = find_method_def(body_node, formula_method_name) audit_on_system_blocks(method_node, formula_method_name) if method_node end NO_ON_SYSTEM_BLOCK_NAMES.each do |formula_block_name| block_node = find_block(body_node, formula_block_name) audit_on_system_blocks(block_node, formula_block_name) if block_node end # Don't restrict OS.mac? or OS.linux? usage in taps; they don't care # as much as we do about e.g. formulae.brew.sh generation, often use # platform-specific URLs and we don't want to add DSLs to support # that case. return if formula_tap != "homebrew-core" audit_arch_conditionals(body_node, allowed_methods: NO_ON_SYSTEM_METHOD_NAMES, allowed_blocks: NO_ON_SYSTEM_BLOCK_NAMES) audit_base_os_conditionals(body_node, allowed_methods: NO_ON_SYSTEM_METHOD_NAMES, allowed_blocks: NO_ON_SYSTEM_BLOCK_NAMES) audit_macos_version_conditionals(body_node, allowed_methods: NO_ON_SYSTEM_METHOD_NAMES, allowed_blocks: NO_ON_SYSTEM_BLOCK_NAMES, recommend_on_system: true) end end # This cop makes sure the `MacOS` module is not used in Linux-facing formula code. class MacOSOnLinux < FormulaCop include OnSystemConditionalsHelper ON_MACOS_BLOCKS = T.let( [:macos, *MACOS_VERSION_OPTIONS].map { |os| :"on_#{os}" }.freeze, T::Array[Symbol], ) sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) audit_macos_references(formula_nodes.body_node, allowed_methods: OnSystemConditionals::NO_ON_SYSTEM_METHOD_NAMES, allowed_blocks: OnSystemConditionals::NO_ON_SYSTEM_BLOCK_NAMES + ON_MACOS_BLOCKS) end end # This cop makes sure that the `generate_completions_from_executable` DSL is used. class GenerateCompletionsDSL < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) install = find_method_def(formula_nodes.body_node, :install) return if install.blank? correctable_shell_completion_node(install) do |node, shell, base_name, executable, subcmd, shell_parameter| # generate_completions_from_executable only applicable if shell is passed next unless shell_parameter.match?(/(bash|zsh|fish|pwsh)/) base_name = base_name.delete_prefix("_").delete_suffix(".fish") shell = shell.to_s.delete_suffix("_completion").to_sym shell_parameter_stripped = shell_parameter .delete_suffix("bash") .delete_suffix("zsh") .delete_suffix("fish") .delete_suffix("pwsh") shell_parameter_format = if shell_parameter_stripped.empty? nil elsif shell_parameter_stripped == "--" :flag elsif shell_parameter_stripped == "--shell=" :arg else shell_parameter_stripped end replacement_args = %w[] replacement_args << executable.source replacement_args << subcmd.source replacement_args << "base_name: \"#{base_name}\"" if base_name != @formula_name replacement_args << "shells: [:#{shell}]" unless shell_parameter_format.nil? replacement_args << "shell_parameter_format: #{shell_parameter_format.inspect}" end offending_node(node) replacement = "generate_completions_from_executable(#{replacement_args.join(", ")})" problem "Use `#{replacement}` instead of `#{T.must(@offensive_node).source}`." do |corrector| corrector.replace(T.must(@offensive_node).source_range, replacement) end end shell_completion_node(install) do |node| next if node.source.include?("<<~") # skip heredoc completion scripts next if node.source.match?(/{.*=>.*}/) # skip commands needing custom ENV variables offending_node(node) problem "Use `generate_completions_from_executable` DSL instead of `#{T.must(@offensive_node).source}`." end end # match ({bash,zsh,fish}_completion/"_?foo{.fish}?").write Utils.safe_popen_read(foo, subcmd, shell_parameter) def_node_search :correctable_shell_completion_node, <<~EOS $(send (begin (send (send nil? ${:bash_completion :zsh_completion :fish_completion}) :/ (str $_))) :write (send (const nil? :Utils) :safe_popen_read $(send (send nil? :bin) :/ (str _)) $(str _) (str $_))) EOS # matches ({bash,zsh,fish}_completion/"_?foo{.fish}?").write output def_node_search :shell_completion_node, <<~EOS $(send (begin (send (send nil? {:bash_completion :zsh_completion :fish_completion}) :/ (str _))) :write _) EOS end # This cop makes sure that the `generate_completions_from_executable` DSL is used with only # a single, combined call for all shells. class SingleGenerateCompletionsDSLCall < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) install = find_method_def(formula_nodes.body_node, :install) return if install.blank? methods = find_every_method_call_by_name(install, :generate_completions_from_executable) return if methods.length <= 1 offenses = [] shells = [] methods.each do |method| next unless method.source.include?("shells:") shells << method.source.match(/shells: \[(:bash|:zsh|:fish)\]/).captures.first offenses << method end return if offenses.blank? T.must(offenses[0...-1]).each_with_index do |node, i| # commands have to be the same to be combined # send_type? matches `bin/"foo"`, str_type? matches remaining command parts, # the rest are kwargs we need to filter out method_commands = node.arguments.filter { |arg| arg.send_type? || arg.str_type? } next_method_commands = offenses[i + 1].arguments.filter { |arg| arg.send_type? || arg.str_type? } if method_commands != next_method_commands shells.delete_at(i) next end offending_node(node) problem "Use a single `generate_completions_from_executable` " \ "call combining all specified shells." do |corrector| # adjust range by -4 and +1 to also include & remove leading spaces and trailing \n corrector.replace(T.must(@offensive_node).source_range.adjust(begin_pos: -4, end_pos: 1), "") end end return if shells.length <= 1 # no shells to combine left offending_node(offenses.last) replacement = if (%w[:bash :zsh :fish] - shells).empty? T.must(@offensive_node).source .sub(/shells: \[(:bash|:zsh|:fish)\]/, "") .sub(", )", ")") # clean up dangling trailing comma .sub("(, ", "(") # clean up dangling leading comma .sub(", , ", ", ") # clean up dangling enclosed comma else T.must(@offensive_node).source.sub(/shells: \[(:bash|:zsh|:fish)\]/, "shells: [#{shells.join(", ")}]") end problem "Use `#{replacement}` instead of `#{T.must(@offensive_node).source}`." do |corrector| corrector.replace(T.must(@offensive_node).source_range, replacement) end end end # This cop checks for other miscellaneous style violations. class Miscellaneous < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? # FileUtils is included in Formula # encfs modifies a file with this name, so check for some leading characters find_instance_method_call(body_node, "FileUtils", nil) do |method_node| problem "No need for `FileUtils.` before `#{method_node.method_name}`" end # Check for long inreplace block vars find_all_blocks(body_node, :inreplace) do |node| block_arg = node.arguments.children.first next if block_arg.source.size <= 1 problem "`inreplace <filenames> do |s|` is preferred over `|#{block_arg.source}|`." end [:rebuild, :version_scheme].each do |method_name| find_method_with_args(body_node, method_name, 0) do problem "`#{method_name} 0` should be removed" end end find_instance_call(body_node, "ARGV") do |_method_node| problem "Use `build.with?` or `build.without?` instead of `ARGV` to check options" end find_instance_method_call(body_node, :man, :+) do |method| next unless (match = regex_match_group(parameters(method).first, /^man[1-8]$/)) problem "`#{method.source}` should be `#{match[0]}`" end # Avoid hard-coding compilers find_every_method_call_by_name(body_node, :system).each do |method| param = parameters(method).first if (match = regex_match_group(param, %r{^(/usr/bin/)?(gcc|clang|cc|c[89]9)(\s|$)})) problem "Use `\#{ENV.cc}` instead of hard-coding `#{match[2]}`" elsif (match = regex_match_group(param, %r{^(/usr/bin/)?((g|clang|c)\+\+)(\s|$)})) problem "Use `\#{ENV.cxx}` instead of hard-coding `#{match[2]}`" end end find_instance_method_call(body_node, "ENV", :[]=) do |method| param = parameters(method)[1] if (match = regex_match_group(param, %r{^(/usr/bin/)?(gcc|clang|cc|c[89]9)(\s|$)})) problem "Use `\#{ENV.cc}` instead of hard-coding `#{match[2]}`" elsif (match = regex_match_group(param, %r{^(/usr/bin/)?((g|clang|c)\+\+)(\s|$)})) problem "Use `\#{ENV.cxx}` instead of hard-coding `#{match[2]}`" end end # Prefer formula path shortcuts in strings formula_path_strings(body_node, :share) do |p| next unless (match = regex_match_group(p, %r{^(/(man))/?})) problem "`\#{share}#{match[1]}` should be `\#{#{match[2]}}`" end formula_path_strings(body_node, :prefix) do |p| if (match = regex_match_group(p, %r{^(/share/(info|man))$})) problem ["`#", "{prefix}", match[1], '` should be `#{', match[2], "}`"].join end if (match = regex_match_group(p, %r{^((/share/man/)(man[1-8]))})) problem ["`#", "{prefix}", match[1], '` should be `#{', match[3], "}`"].join end if (match = regex_match_group(p, %r{^(/(bin|include|libexec|lib|sbin|share|Frameworks))}i)) problem ["`#", "{prefix}", match[1], '` should be `#{', match[2].downcase, "}`"].join end end find_every_method_call_by_name(body_node, :depends_on).each do |method| key, value = destructure_hash(parameters(method).first) next if key.nil? || value.nil? next unless (match = regex_match_group(value, /^(lua|perl|python|ruby)(\d*)/)) problem "#{match[1]} modules should be vendored rather than using deprecated `#{method.source}`" end find_every_method_call_by_name(body_node, :system).each do |method| next unless (match = regex_match_group(parameters(method).first, /^(env|export)(\s+)?/)) problem "Use `ENV` instead of invoking `#{match[1]}` to modify the environment" end find_every_method_call_by_name(body_node, :depends_on).each do |method| param = parameters(method).first dep, option_child_nodes = hash_dep(param) next if dep.nil? || option_child_nodes.empty? option_child_nodes.each do |option| find_strings(option).each do |dependency| next unless (match = regex_match_group(dependency, /(with(out)?-\w+|c\+\+11)/)) problem "Dependency '#{string_content(dep)}' should not use option `#{match[0]}`" end end end find_instance_method_call(body_node, :version, :==) do |method| next unless parameters_passed?(method, ["HEAD"])
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
true
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/negate_include.rb
Library/Homebrew/rubocops/negate_include.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # Enforces the use of `collection.exclude?(obj)` # over `!collection.include?(obj)`. # # NOTE: This cop is unsafe because false positives will occur for # receiver objects that do not have an `#exclude?` method (e.g. `IPAddr`). # # ### Example # # ```ruby # # bad # !array.include?(2) # !hash.include?(:key) # # # good # array.exclude?(2) # hash.exclude?(:key) # ``` class NegateInclude < Base extend AutoCorrector MSG = "Use `.exclude?` and remove the negation part." RESTRICT_ON_SEND = [:!].freeze def_node_matcher :negate_include_call?, <<~PATTERN (send (send $!nil? :include? $_) :!) PATTERN sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return unless (receiver, obj = negate_include_call?(node)) add_offense(node) do |corrector| corrector.replace(node, "#{receiver.source}.exclude?(#{obj.source})") 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/rubocops/files.rb
Library/Homebrew/rubocops/files.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop makes sure that a formula's file permissions are correct. class Files < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return unless file_path # Codespaces routinely screws up all permissions so don't complain there. return if ENV["CODESPACES"] || ENV["HOMEBREW_CODESPACES"] offending_node(formula_nodes.node) actual_mode = File.stat(file_path).mode # Check that the file is world-readable. if actual_mode & 0444 != 0444 problem format("Incorrect file permissions (%03<actual>o): chmod %<wanted>s %<path>s", actual: actual_mode & 0777, wanted: "a+r", path: file_path) end # Check that the file is user-writeable. if actual_mode & 0200 != 0200 problem format("Incorrect file permissions (%03<actual>o): chmod %<wanted>s %<path>s", actual: actual_mode & 0777, wanted: "u+w", path: file_path) end # Check that the file is *not* other-writeable. return if actual_mode & 0002 != 002 problem format("Incorrect file permissions (%03<actual>o): chmod %<wanted>s %<path>s", actual: actual_mode & 0777, wanted: "o-w", path: file_path) end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/version.rb
Library/Homebrew/rubocops/version.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop makes sure that a `version` is in the correct format. class Version < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) version_node = find_node_method_by_name(formula_nodes.body_node, :version) return unless version_node version = string_content(parameters(version_node).first) problem "Version is set to an empty string" if version.empty? problem "Version #{version} should not have a leading 'v'" if version.start_with?("v") return unless version.match?(/_\d+$/) problem "Version #{version} should not end with an underline and a number" 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/rubocops/desc.rb
Library/Homebrew/rubocops/desc.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" require "rubocops/shared/desc_helper" module RuboCop module Cop module FormulaAudit # This cop audits `desc` in formulae. # See the {DescHelper} module for details of the checks. class Desc < FormulaCop include DescHelper extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node @name = T.let(@formula_name, T.nilable(String)) desc_call = find_node_method_by_name(body_node, :desc) offending_node(formula_nodes.class_node) if body_node.nil? audit_desc(:formula, @name, desc_call) 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/rubocops/deprecate_disable.rb
Library/Homebrew/rubocops/deprecate_disable.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits `deprecate!` and `disable!` dates. class DeprecateDisableDate < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node [:deprecate!, :disable!].each do |method| node = find_node_method_by_name(body_node, method) next if node.nil? date(node) do |date_node| Date.iso8601(string_content(date_node)) rescue ArgumentError fixed_date_string = Date.parse(string_content(date_node)).iso8601 offending_node(date_node) problem "Use `#{fixed_date_string}` to comply with ISO 8601" do |corrector| corrector.replace(date_node.source_range, "\"#{fixed_date_string}\"") end end end end def_node_search :date, <<~EOS (pair (sym :date) $str) EOS end # This cop audits `deprecate!` and `disable!` reasons. class DeprecateDisableReason < FormulaCop extend AutoCorrector PUNCTUATION_MARKS = %w[. ! ?].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node [:deprecate!, :disable!].each do |method| node = find_node_method_by_name(body_node, method) next if node.nil? reason_found = T.let(false, T::Boolean) reason(node) do |reason_node| reason_found = true next if reason_node.sym_type? offending_node(reason_node) reason_string = string_content(reason_node) if reason_string.start_with?("it ") problem "Do not start the reason with `it`" do |corrector| corrector.replace(T.must(@offensive_node).source_range, "\"#{reason_string[3..]}\"") end end if PUNCTUATION_MARKS.include?(reason_string[-1]) problem "Do not end the reason with a punctuation mark" do |corrector| corrector.replace(T.must(@offensive_node).source_range, "\"#{reason_string.chop}\"") end end end next if reason_found case method when :deprecate! problem 'Add a reason for deprecation: `deprecate! because: "..."`' when :disable! problem 'Add a reason for disabling: `disable! because: "..."`' end end end def_node_search :reason, <<~EOS (pair (sym :because) ${str sym}) 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/rubocops/io_read.rb
Library/Homebrew/rubocops/io_read.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # This cop restricts usage of `IO.read` functions for security reasons. class IORead < Base MSG = "The use of `IO.%<method>s` is a security risk." RESTRICT_ON_SEND = [:read, :readlines].freeze sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return if node.receiver != s(:const, nil, :IO) return if safe?(node.arguments.first) add_offense(node, message: format(MSG, method: node.method_name)) end private sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def safe?(node) if node.str_type? !node.str_content.empty? && !node.str_content.start_with?("|") elsif node.dstr_type? || (node.send_type? && T.cast(node, RuboCop::AST::SendNode).method?(:+)) safe?(node.children.first) else false end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/conflicts.rb
Library/Homebrew/rubocops/conflicts.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits versioned formulae for `conflicts_with`. class Conflicts < FormulaCop extend AutoCorrector MSG = "Versioned formulae should not use `conflicts_with`. " \ "Use `keg_only :versioned_formula` instead." sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? find_method_calls_by_name(body_node, :conflicts_with).each do |conflicts_with_call| next unless parameters(conflicts_with_call).last.respond_to? :values reason = parameters(conflicts_with_call).last.values.first offending_node(reason) name = Regexp.new(T.must(@formula_name), Regexp::IGNORECASE) reason_text = string_content(reason).sub(name, "") first_word = reason_text.split.first if reason_text.match?(/\A[A-Z]/) problem "'#{first_word}' from the `conflicts_with` reason " \ "should be '#{first_word.downcase}'." do |corrector| reason_text[0] = reason_text[0].downcase corrector.replace(reason.source_range, "\"#{reason_text}\"") end end next unless reason_text.end_with?(".") problem "`conflicts_with` reason should not end with a period." do |corrector| corrector.replace(reason.source_range, "\"#{reason_text.chop}\"") end end return unless versioned_formula? if !tap_style_exception?(:versioned_formulae_conflicts_allowlist) && method_called_ever?(body_node, :conflicts_with) problem MSG do |corrector| corrector.replace(T.must(@offensive_node).source_range, "keg_only :versioned_formula") end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/checksum.rb
Library/Homebrew/rubocops/checksum.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop makes sure that deprecated checksums are not used. class Checksum < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node problem "MD5 checksums are deprecated, please use SHA-256" if method_called_ever?(body_node, :md5) problem "SHA1 checksums are deprecated, please use SHA-256" if method_called_ever?(body_node, :sha1) sha256_calls = find_every_method_call_by_name(body_node, :sha256) sha256_calls.each do |sha256_call| sha256_node = get_checksum_node(sha256_call) audit_sha256(sha256_node) end end sig { params(checksum: T.nilable(RuboCop::AST::Node)).void } def audit_sha256(checksum) return if checksum.nil? if regex_match_group(checksum, /^$/) problem "`sha256` is empty" return end if string_content(checksum).size != 64 && regex_match_group(checksum, /^\w*$/) problem "`sha256` should be 64 characters" end return unless regex_match_group(checksum, /[^a-f0-9]+/i) add_offense(T.must(@offensive_source_range), message: "`sha256` contains invalid characters") end end # This cop makes sure that checksum strings are lowercase. class ChecksumCase < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) sha256_calls = find_every_method_call_by_name(formula_nodes.body_node, :sha256) sha256_calls.each do |sha256_call| checksum = get_checksum_node(sha256_call) next if checksum.nil? next unless regex_match_group(checksum, /[A-F]+/) add_offense(@offensive_source_range, message: "`sha256` should be lowercase") do |corrector| correction = T.must(@offensive_node).source.downcase corrector.insert_before(T.must(@offensive_node).source_range, correction) corrector.remove(T.must(@offensive_node).source_range) end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/install_bundler_gems.rb
Library/Homebrew/rubocops/install_bundler_gems.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # Enforces the use of `Homebrew.install_bundler_gems!` in dev-cmd. class InstallBundlerGems < Base MSG = "Only use `Homebrew.install_bundler_gems!` in dev-cmd." RESTRICT_ON_SEND = [:install_bundler_gems!].freeze sig { params(node: RuboCop::AST::Node).void } def on_send(node) file_path = processed_source.file_path return if file_path.match?(%r{/(dev-cmd/.+|standalone/init|startup/bootsnap)\.rb\z}) add_offense(node) 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/rubocops/text.rb
Library/Homebrew/rubocops/text.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop checks for various problems in a formula's source code. class Text < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) node = formula_nodes.node full_source_content = source_buffer(node).source if (match = full_source_content.match(/^require ['"]formula['"]$/)) range = source_range(source_buffer(node), match.pre_match.count("\n") + 1, 0, match[0].length) add_offense(range, message: "`#{match}` is now unnecessary") do |corrector| corrector.remove(range_with_surrounding_space(range:)) end end return if (body_node = formula_nodes.body_node).nil? if find_method_def(body_node, :plist) problem "`def plist` is deprecated. Please use services instead: https://docs.brew.sh/Formula-Cookbook#service-files" end if (depends_on?("openssl") || depends_on?("openssl@3")) && depends_on?("libressl") problem "Formulae should not depend on both OpenSSL and LibreSSL (even optionally)." end if formula_tap == "homebrew-core" if depends_on?("veclibfort") || depends_on?("lapack") problem "Formulae in homebrew/core should use OpenBLAS as the default serial linear algebra library." end if find_node_method_by_name(body_node, :keg_only)&.source&.include?("HOMEBREW_PREFIX") problem "`keg_only` reason should not include `$HOMEBREW_PREFIX` " \ "as it creates confusing `brew info` output." end end # processed_source.ast is passed instead of body_node because `require` would be outside body_node find_method_with_args(processed_source.ast, :require, "language/go") do problem '`require "language/go"` is no longer necessary or correct' end find_instance_method_call(body_node, "Formula", :factory) do problem "`Formula.factory(name)` is deprecated in favour of `Formula[name]`" end find_method_with_args(body_node, :revision, 0) do problem "`revision 0` is unnecessary" end find_method_with_args(body_node, :system, "xcodebuild") do problem "Use `xcodebuild *args` instead of `system 'xcodebuild', *args`" end if !depends_on?(:xcode) && method_called_ever?(body_node, :xcodebuild) problem "`xcodebuild` needs an Xcode dependency" end if (method_node = find_method_def(body_node, :install)) find_method_with_args(method_node, :system, "go", "get") do problem "Do not use `go get`. Please ask upstream to implement Go vendoring" end find_method_with_args(method_node, :system, "cargo", "build") do |m| next if parameters_passed?(m, [/--lib/]) problem 'Use `"cargo", "install", *std_cargo_args`' end end find_method_with_args(body_node, :system, "dep", "ensure") do |d| next if parameters_passed?(d, [/vendor-only/]) next if @formula_name == "goose" # needed in 2.3.0 problem 'Use `"dep", "ensure", "-vendor-only"`' end find_every_method_call_by_name(body_node, :system).each do |m| next unless parameters_passed?(m, [/make && make/]) offending_node(m) problem "Use separate `make` calls" end find_every_method_call_by_name(body_node, :+).each do |plus_node| next unless plus_node.receiver&.send_type? next unless plus_node.first_argument&.str_type? receiver_method = plus_node.receiver.method_name path_arg = plus_node.first_argument.str_content case receiver_method when :prefix next unless (match = path_arg.match(%r{^(bin|include|libexec|lib|sbin|share|Frameworks)(?:/| |$)})) offending_node(plus_node) problem "Use `#{match[1].downcase}` instead of `prefix + \"#{match[1]}\"`" when :bin, :include, :libexec, :lib, :sbin, :share next if path_arg.empty? offending_node(plus_node) good = "#{receiver_method}/\"#{path_arg}\"" problem "Use `#{good}` instead of `#{plus_node.source}`" do |corrector| corrector.replace(plus_node.loc.expression, good) end end end body_node.each_descendant(:dstr) do |dstr_node| dstr_node.each_descendant(:begin) do |interpolation_node| next unless interpolation_node.source.match?(/#\{\w+\s*\+\s*['"][^}]+\}/) offending_node(interpolation_node) problem "Do not concatenate paths in string interpolation" end end end end end module FormulaAuditStrict # This cop contains stricter checks for various problems in a formula's source code. class Text < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? find_method_with_args(body_node, :env, :userpaths) do problem "`env :userpaths` in homebrew/core formulae is deprecated" end share_path_starts_with(body_node, T.must(@formula_name)) do |share_node| offending_node(share_node) problem "Use `pkgshare` instead of `share/\"#{@formula_name}\"`" end interpolated_share_path_starts_with(body_node, "/#{@formula_name}") do |share_node| offending_node(share_node) problem "Use `\#{pkgshare}` instead of `\#{share}/#{@formula_name}`" end interpolated_bin_path_starts_with(body_node, "/#{@formula_name}") do |bin_node| next if bin_node.ancestors.any?(&:array_type?) offending_node(bin_node) cmd = bin_node.source.match(%r{\#{bin}/(\S+)})[1]&.delete_suffix('"') || @formula_name problem "Use `bin/\"#{cmd}\"` instead of `\"\#{bin}/#{cmd}\"`" do |corrector| corrector.replace(bin_node.loc.expression, "bin/\"#{cmd}\"") end end return if formula_tap != "homebrew-core" find_method_with_args(body_node, :env, :std) do problem "`env :std` in homebrew/core formulae is deprecated" end end # Check whether value starts with the formula name and then a "/", " " or EOS. # If we're checking for "#\\{bin}", we also check for "-" b/c similar binaries don't also need interpolation. sig { params(path: String, starts_with: String, bin: T::Boolean).returns(T::Boolean) } def path_starts_with?(path, starts_with, bin: false) ending = bin ? "/|-|$" : "/| |$" path.match?(/^#{Regexp.escape(starts_with)}(#{ending})/) end sig { params(path: String, starts_with: String).returns(T::Boolean) } def path_starts_with_bin?(path, starts_with) return false if path.include?(" ") path_starts_with?(path, starts_with, bin: true) end # Find "#{share}/foo" def_node_search :interpolated_share_path_starts_with, <<~EOS $(dstr (begin (send nil? :share)) (str #path_starts_with?(%1))) EOS # Find "#{bin}/foo" and "#{bin}/foo-bar" def_node_search :interpolated_bin_path_starts_with, <<~EOS $(dstr (begin (send nil? :bin)) (str #path_starts_with_bin?(%1))) EOS # Find share/"foo" def_node_search :share_path_starts_with, <<~EOS $(send (send nil? :share) :/ (str #path_starts_with?(%1))) 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/rubocops/shell_commands.rb
Library/Homebrew/rubocops/shell_commands.rb
# typed: strict # frozen_string_literal: true require "extend/array" require "rubocops/shared/helper_functions" require "shellwords" module RuboCop module Cop module Homebrew # https://github.com/ruby/ruby/blob/v2_6_3/process.c#L2430-L2460 SHELL_BUILTINS = %w[ ! . : break case continue do done elif else esac eval exec exit export fi for if in readonly return set shift then times trap unset until while ].freeze private_constant :SHELL_BUILTINS # https://github.com/ruby/ruby/blob/v2_6_3/process.c#L2495 SHELL_METACHARACTERS = %W[* ? { } [ ] < > ( ) ~ & | \\ $ ; ' ` " \n #].freeze private_constant :SHELL_METACHARACTERS # This cop makes sure that shell command arguments are separated. class ShellCommands < Base include HelperFunctions extend AutoCorrector MSG = "Separate `%<method>s` commands into `%<good_args>s`" TARGET_METHODS = [ [nil, :system], [nil, :safe_system], [nil, :quiet_system], [:Utils, :popen_read], [:Utils, :safe_popen_read], [:Utils, :popen_write], [:Utils, :safe_popen_write], ].freeze private_constant :TARGET_METHODS RESTRICT_ON_SEND = T.let( TARGET_METHODS.map(&:second).uniq.freeze, T::Array[T.nilable(Symbol)], ) sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) TARGET_METHODS.each do |target_class, target_method| next if node.method_name != target_method target_receivers = if target_class.nil? [nil, s(:const, nil, :Kernel), s(:const, nil, :Homebrew)] else [s(:const, nil, target_class)] end next unless target_receivers.include?(node.receiver) first_arg = node.arguments.first arg_count = node.arguments.count if first_arg&.hash_type? # popen methods allow env hash first_arg = node.arguments.second arg_count -= 1 end next if first_arg.nil? || arg_count >= 2 first_arg_str = string_content(first_arg) stripped_first_arg_str = string_content(first_arg, strip_dynamic: true) split_args = first_arg_str.shellsplit next if split_args.count <= 1 # Only separate when no shell metacharacters are present command = split_args.first next if SHELL_BUILTINS.any?(command) next if command&.include?("=") next if SHELL_METACHARACTERS.any? { |meta| stripped_first_arg_str.include?(meta) } good_args = split_args.map { |arg| "\"#{arg}\"" }.join(", ") method_string = if target_class "#{target_class}.#{target_method}" else target_method.to_s end add_offense(first_arg, message: format(MSG, method: method_string, good_args:)) do |corrector| corrector.replace(first_arg.source_range, good_args) end end end end # This cop disallows shell metacharacters in `exec` calls. class ExecShellMetacharacters < Base include HelperFunctions MSG = "Don't use shell metacharacters in `exec`. " \ "Implement the logic in Ruby instead, using methods like `$stdout.reopen`." RESTRICT_ON_SEND = [:exec].freeze sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return if node.receiver.present? && node.receiver != s(:const, nil, :Kernel) return if node.arguments.count != 1 stripped_arg_str = string_content(node.arguments.first, strip_dynamic: true) command = string_content(node.arguments.first).shellsplit.first return if SHELL_BUILTINS.none?(command) && !command&.include?("=") && SHELL_METACHARACTERS.none? { |meta| stripped_arg_str.include?(meta) } add_offense(node.arguments.first, message: MSG) 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/rubocops/options.rb
Library/Homebrew/rubocops/options.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits `option`s in formulae. class Options < FormulaCop DEP_OPTION = "Formulae in homebrew/core should not use `deprecated_option`." OPTION = "Formulae in homebrew/core should not use `option`." sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? option_call_nodes = find_every_method_call_by_name(body_node, :option) option_call_nodes.each do |option_call| option = parameters(option_call).first offending_node(option_call) option = string_content(option) unless /with(out)?-/.match?(option) problem "Options should begin with `with` or `without`. " \ "Migrate '--#{option}' with `deprecated_option`." end next unless option =~ /^with(out)?-(?:checks?|tests)$/ next if depends_on?("check", :optional, :recommended) problem "Use '--with#{Regexp.last_match(1)}-test' instead of '--#{option}'. " \ "Migrate '--#{option}' with `deprecated_option`." end return if formula_tap != "homebrew-core" problem DEP_OPTION if method_called_ever?(body_node, :deprecated_option) problem OPTION if method_called_ever?(body_node, :option) 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/rubocops/caveats.rb
Library/Homebrew/rubocops/caveats.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop ensures that caveats don't have problematic text or logic. # # ### Example # # ```ruby # # bad # def caveats # if File.exist?("/etc/issue") # "This caveat only when file exists that won't work with JSON API." # end # end # # # good # def caveats # "This caveat always works regardless of the JSON API." # end # # # bad # def caveats # <<~EOS # Use `setuid` to allow running the executable by non-root users. # EOS # end # # # good # def caveats # <<~EOS # Use `sudo` to run the executable. # EOS # end # ``` class Caveats < FormulaCop sig { override.params(_formula_nodes: FormulaNodes).void } def audit_formula(_formula_nodes) caveats_strings.each do |n| if regex_match_group(n, /\bsetuid\b/i) problem "Instead of recommending `setuid` in the caveats, suggest `sudo`." end problem "Don't use ANSI escape codes in the caveats." if regex_match_group(n, /\e/) end return if formula_tap != "homebrew-core" # Forbid dynamic logic in caveats (only if/else/unless) caveats_method = find_method_def(@body, :caveats) return unless caveats_method dynamic_nodes = caveats_method.each_descendant.select do |descendant| descendant.type == :if end dynamic_nodes.each do |node| @offensive_node = node problem "Don't use dynamic logic (if/else/unless) in caveats." 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/rubocops/presence.rb
Library/Homebrew/rubocops/presence.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true module RuboCop module Cop module Homebrew # Checks code that can be written more easily using # `Object#presence` defined by Active Support. # # ### Examples # # ```ruby # # bad # a.present? ? a : nil # # # bad # !a.present? ? nil : a # # # bad # a.blank? ? nil : a # # # bad # !a.blank? ? a : nil # # # good # a.presence # ``` # # ```ruby # # bad # a.present? ? a : b # # # bad # !a.present? ? b : a # # # bad # a.blank? ? b : a # # # bad # !a.blank? ? a : b # # # good # a.presence || b # ``` class Presence < Base include RangeHelp extend AutoCorrector MSG = "Use `%<prefer>s` instead of `%<current>s`." def_node_matcher :redundant_receiver_and_other, <<~PATTERN { (if (send $_recv :present?) _recv $!begin ) (if (send $_recv :blank?) $!begin _recv ) } PATTERN def_node_matcher :redundant_negative_receiver_and_other, <<~PATTERN { (if (send (send $_recv :present?) :!) $!begin _recv ) (if (send (send $_recv :blank?) :!) _recv $!begin ) } PATTERN sig { params(node: RuboCop::AST::IfNode).void } def on_if(node) return if ignore_if_node?(node) redundant_receiver_and_other(node) do |receiver, other| return if ignore_other_node?(other) || receiver.nil? register_offense(node, receiver, other) end redundant_negative_receiver_and_other(node) do |receiver, other| return if ignore_other_node?(other) || receiver.nil? register_offense(node, receiver, other) end end private def register_offense(node, receiver, other) add_offense(node, message: message(node, receiver, other)) do |corrector| corrector.replace(node, replacement(receiver, other, node.left_sibling)) end end def ignore_if_node?(node) node.elsif? end def ignore_other_node?(node) node && (node.if_type? || node.rescue_type? || node.while_type?) end def message(node, receiver, other) prefer = replacement(receiver, other, node.left_sibling).gsub(/^\s*|\n/, "") current = current(node).gsub(/^\s*|\n/, "") format(MSG, prefer:, current:) end def current(node) if !node.ternary? && node.source.include?("\n") "#{node.loc.keyword.with(end_pos: node.condition.loc.selector.end_pos).source} ... end" else node.source.gsub(/\n\s*/, " ") end end def replacement(receiver, other, left_sibling) or_source = if other&.send_type? build_source_for_or_method(other) elsif other.nil? || other.nil_type? "" else " || #{other.source}" end replaced = "#{receiver.source}.presence#{or_source}" left_sibling ? "(#{replaced})" : replaced end def build_source_for_or_method(other) if other.parenthesized? || other.method?("[]") || other.arithmetic_operation? || !other.arguments? " || #{other.source}" else method = method_range(other).source arguments = other.arguments.map(&:source).join(", ") " || #{method}(#{arguments})" end end def method_range(node) range_between(node.source_range.begin_pos, node.first_argument.source_range.begin_pos - 1) 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/rubocops/blank.rb
Library/Homebrew/rubocops/blank.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # Checks for code that can be simplified using `Object#blank?`. # # NOTE: Auto-correction for this cop is unsafe because `' '.empty?` returns `false`, # but `' '.blank?` returns `true`. Therefore, auto-correction is not compatible # if the receiver is a non-empty blank string. # # ### Example # # ```ruby # # bad # foo.nil? || foo.empty? # foo == nil || foo.empty? # # # good # foo.blank? # ``` class Blank < Base extend AutoCorrector MSG = "Use `%<prefer>s` instead of `%<current>s`." # `(send nil $_)` is not actually a valid match for an offense. Nodes # that have a single method call on the left hand side # (`bar || foo.empty?`) will blow up when checking # `(send (:nil) :== $_)`. def_node_matcher :nil_or_empty?, <<~PATTERN (or { (send $_ :!) (send $_ :nil?) (send $_ :== nil) (send nil :== $_) } { (send $_ :empty?) (send (send (send $_ :empty?) :!) :!) } ) PATTERN sig { params(node: RuboCop::AST::Node).void } def on_or(node) nil_or_empty?(node) do |var1, var2| return if var1 != var2 message = format(MSG, prefer: replacement(var1), current: node.source) add_offense(node, message:) do |corrector| autocorrect(corrector, node) end end end private sig { params(corrector: RuboCop::Cop::Corrector, node: RuboCop::AST::Node).void } def autocorrect(corrector, node) variable1, _variable2 = nil_or_empty?(node) range = node.source_range corrector.replace(range, replacement(variable1)) end sig { params(node: T.nilable(RuboCop::AST::Node)).returns(String) } def replacement(node) node.respond_to?(:source) ? "#{node&.source}.blank?" : "blank?" 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/rubocops/livecheck.rb
Library/Homebrew/rubocops/livecheck.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop ensures that no other livecheck information is provided for # skipped formulae. class LivecheckSkip < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) livecheck_node = find_block(formula_nodes.body_node, :livecheck) return if livecheck_node.blank? skip = find_every_method_call_by_name(livecheck_node, :skip).first return if skip.blank? return if find_every_method_call_by_name(livecheck_node).length < 3 offending_node(livecheck_node) problem "Skipped formulae must not contain other livecheck information." do |corrector| skip = find_every_method_call_by_name(livecheck_node, :skip).first skip = find_strings(skip).first skip = string_content(skip) if skip.present? corrector.replace( livecheck_node.source_range, <<~EOS.strip, livecheck do skip#{" \"#{skip}\"" if skip.present?} end EOS ) end end end # This cop ensures that a `url` is specified in the `livecheck` block. class LivecheckUrlProvided < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) livecheck_node = find_block(formula_nodes.body_node, :livecheck) return unless livecheck_node url_node = find_every_method_call_by_name(livecheck_node, :url).first return if url_node # A regex and/or strategy is specific to a particular URL, so we # should require an explicit URL. regex_node = find_every_method_call_by_name(livecheck_node, :regex).first strategy_node = find_every_method_call_by_name(livecheck_node, :strategy).first return if !regex_node && !strategy_node offending_node(livecheck_node) problem "A `url` should be provided when `regex` or `strategy` are used." end end # This cop ensures that a supported symbol (`head`, `stable, `homepage`) # is used when the livecheck `url` is identical to one of these formula URLs. class LivecheckUrlSymbol < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node livecheck_node = find_block(body_node, :livecheck) return if livecheck_node.blank? skip = find_every_method_call_by_name(livecheck_node, :skip).first.present? return if skip.present? livecheck_url_node = find_every_method_call_by_name(livecheck_node, :url).first livecheck_url = find_strings(livecheck_url_node).first return if livecheck_url.blank? livecheck_url = string_content(livecheck_url) head = find_every_method_call_by_name(body_node, :head).first head_url = find_strings(head).first if head.present? && head_url.blank? head = find_every_method_call_by_name(head, :url).first head_url = find_strings(head).first end head_url = string_content(head_url) if head_url.present? stable = find_every_method_call_by_name(body_node, :url).first stable_url = find_strings(stable).first if stable_url.blank? stable = find_every_method_call_by_name(body_node, :stable).first stable = find_every_method_call_by_name(stable, :url).first stable_url = find_strings(stable).first end stable_url = string_content(stable_url) if stable_url.present? homepage = find_every_method_call_by_name(body_node, :homepage).first homepage_url = string_content(find_strings(homepage).first) if homepage.present? formula_urls = { head: head_url, stable: stable_url, homepage: homepage_url }.compact formula_urls.each do |symbol, url| next if url != livecheck_url && url != "#{livecheck_url}/" && "#{url}/" != livecheck_url offending_node(livecheck_url_node) problem "Use `url :#{symbol}`" do |corrector| corrector.replace(livecheck_url_node.source_range, "url :#{symbol}") end break end end end # This cop ensures that the `regex` call in the `livecheck` block uses parentheses. class LivecheckRegexParentheses < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) livecheck_node = find_block(formula_nodes.body_node, :livecheck) return if livecheck_node.blank? skip = find_every_method_call_by_name(livecheck_node, :skip).first.present? return if skip.present? livecheck_regex_node = find_every_method_call_by_name(livecheck_node, :regex).first return if livecheck_regex_node.blank? return if parentheses?(livecheck_regex_node) offending_node(livecheck_regex_node) problem "The `regex` call should always use parentheses." do |corrector| pattern = livecheck_regex_node.source.split[1..].join corrector.replace(livecheck_regex_node.source_range, "regex(#{pattern})") end end end # This cop ensures that the pattern provided to livecheck's `regex` uses `\.t` instead of # `\.tgz`, `\.tar.gz` and variants. class LivecheckRegexExtension < FormulaCop extend AutoCorrector TAR_PATTERN = /\\?\.t(ar|(g|l|x)z$|[bz2]{2,4}$)(\\?\.((g|l|x)z)|[bz2]{2,4}|Z)?$/i sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) livecheck_node = find_block(formula_nodes.body_node, :livecheck) return if livecheck_node.blank? skip = find_every_method_call_by_name(livecheck_node, :skip).first.present? return if skip.present? livecheck_regex_node = find_every_method_call_by_name(livecheck_node, :regex).first return if livecheck_regex_node.blank? regex_node = livecheck_regex_node.descendants.first pattern = string_content(find_strings(regex_node).first) match = pattern.match(TAR_PATTERN) return if match.blank? offending_node(regex_node) problem "Use `\\.t` instead of `#{match}`" do |corrector| node = find_strings(regex_node).first correct = node.source.gsub(TAR_PATTERN, "\\.t") corrector.replace(node.source_range, correct) end end end # This cop ensures that a `regex` is provided when `strategy :page_match` is specified # in the `livecheck` block. class LivecheckRegexIfPageMatch < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) livecheck_node = find_block(formula_nodes.body_node, :livecheck) return if livecheck_node.blank? skip = find_every_method_call_by_name(livecheck_node, :skip).first.present? return if skip.present? livecheck_strategy_node = find_every_method_call_by_name(livecheck_node, :strategy).first return if livecheck_strategy_node.blank? strategy = livecheck_strategy_node.descendants.first.source return if strategy != ":page_match" livecheck_regex_node = find_every_method_call_by_name(livecheck_node, :regex).first return if livecheck_regex_node.present? offending_node(livecheck_node) problem "A `regex` is required if `strategy :page_match` is present." end end # This cop ensures that the `regex` provided to livecheck is case-insensitive, # unless sensitivity is explicitly required for proper matching. class LivecheckRegexCaseInsensitive < FormulaCop extend AutoCorrector MSG = "Regexes should be case-insensitive unless sensitivity is explicitly required for proper matching." sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if tap_style_exception? :regex_case_sensitive_allowlist livecheck_node = find_block(formula_nodes.body_node, :livecheck) return if livecheck_node.blank? skip = find_every_method_call_by_name(livecheck_node, :skip).first.present? return if skip.present? livecheck_regex_node = find_every_method_call_by_name(livecheck_node, :regex).first return if livecheck_regex_node.blank? regex_node = livecheck_regex_node.descendants.first options_node = regex_node.regopt return if options_node.source.include?("i") offending_node(regex_node) problem MSG do |corrector| node = regex_node.regopt corrector.replace(node.source_range, "i#{node.source}".chars.sort.join) 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/rubocops/safe_navigation_with_blank.rb
Library/Homebrew/rubocops/safe_navigation_with_blank.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # Checks to make sure safe navigation isn't used with `blank?` in # a conditional. # # NOTE: While the safe navigation operator is generally a good idea, when # checking `foo&.blank?` in a conditional, `foo` being `nil` will actually # do the opposite of what the author intends: # # ```ruby # foo&.blank? #=> nil # foo.blank? #=> true # ``` # # ### Example # # ```ruby # # bad # do_something if foo&.blank? # do_something unless foo&.blank? # # # good # do_something if foo.blank? # do_something unless foo.blank? # ``` class SafeNavigationWithBlank < Base extend AutoCorrector MSG = "Avoid calling `blank?` with the safe navigation operator in conditionals." def_node_matcher :safe_navigation_blank_in_conditional?, <<~PATTERN (if $(csend ... :blank?) ...) PATTERN sig { params(node: RuboCop::AST::IfNode).void } def on_if(node) return unless safe_navigation_blank_in_conditional?(node) add_offense(node) do |corrector| corrector.replace(safe_navigation_blank_in_conditional?(node).location.dot, ".") 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/rubocops/keg_only.rb
Library/Homebrew/rubocops/keg_only.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop makes sure that a `keg_only` reason has the correct format. class KegOnly < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) keg_only_node = find_node_method_by_name(formula_nodes.body_node, :keg_only) return unless keg_only_node allowlist = %w[ Apple macOS OS Homebrew Xcode GPG GNOME BSD Firefox ].freeze reason = parameters(keg_only_node).first offending_node(reason) name = Regexp.new(T.must(@formula_name), Regexp::IGNORECASE) reason = string_content(reason).sub(name, "") first_word = reason.split.first if /\A[A-Z]/.match?(reason) && !reason.start_with?(*allowlist) problem "'#{first_word}' from the `keg_only` reason should be '#{first_word.downcase}'." do |corrector| reason[0] = reason[0].downcase corrector.replace(T.must(@offensive_node).source_range, "\"#{reason}\"") end end return unless reason.end_with?(".") problem "`keg_only` reason should not end with a period." do |corrector| corrector.replace(T.must(@offensive_node).source_range, "\"#{reason.chop}\"") end end sig { params(node: RuboCop::AST::Node).void } def autocorrect(node) lambda do |corrector| reason = string_content(node) reason[0] = reason[0].downcase reason = reason.delete_suffix(".") corrector.replace(node.source_range, "\"#{reason}\"") 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/rubocops/move_to_extend_os.rb
Library/Homebrew/rubocops/move_to_extend_os.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # This cop ensures that platform specific code ends up in `extend/os`. class MoveToExtendOS < Base MSG = "Move `OS.linux?` and `OS.mac?` calls to `extend/os`." def_node_matcher :os_check?, <<~PATTERN (send (const nil? :OS) {:mac? | :linux?}) PATTERN sig { params(node: RuboCop::AST::Node).void } def on_send(node) return unless os_check?(node) add_offense(node) 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/rubocops/components_redundancy.rb
Library/Homebrew/rubocops/components_redundancy.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop checks if redundant components are present and for other component errors. # # - `url|checksum|mirror|version` should be inside `stable` block # - `head` and `head do` should not be simultaneously present # - `bottle :unneeded`/`:disable` and `bottle do` should not be simultaneously present # - `stable do` should not be present without a `head` spec # - `stable do` should not be present with only `url|checksum|mirror|version` # - `head do` should not be present with only `url|branch` class ComponentsRedundancy < FormulaCop HEAD_MSG = "`head` and `head do` should not be simultaneously present" BOTTLE_MSG = "`bottle :modifier` and `bottle do` should not be simultaneously present" STABLE_MSG = "`stable do` should not be present without a `head` spec" STABLE_BLOCK_METHODS = [:url, :sha256, :mirror, :version].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? urls = find_method_calls_by_name(body_node, :url) urls.each do |url| url.arguments.each do |arg| next if arg.class != RuboCop::AST::HashNode url_args = arg.keys.each.map(&:value) if method_called?(body_node, :sha256) && url_args.include?(:tag) && url_args.include?(:revision) problem "Do not use both `sha256` and `tag:`/`revision:`." end end end stable_block = find_block(body_node, :stable) if stable_block STABLE_BLOCK_METHODS.each do |method_name| problem "`#{method_name}` should be put inside `stable` block" if method_called?(body_node, method_name) end unless stable_block.body.nil? child_nodes = stable_block.body.begin_type? ? stable_block.body.child_nodes : [stable_block.body] if child_nodes.all? { |n| n.send_type? && STABLE_BLOCK_METHODS.include?(n.method_name) } problem "`stable do` should not be present with only #{STABLE_BLOCK_METHODS.join("/")}" end end end head_block = find_block(body_node, :head) if head_block && !head_block.body.nil? child_nodes = head_block.body.begin_type? ? head_block.body.child_nodes : [head_block.body] shorthand_head_methods = [:url, :branch] if child_nodes.all? { |n| n.send_type? && shorthand_head_methods.include?(n.method_name) } problem "`head do` should not be present with only #{shorthand_head_methods.join("/")}" end end problem HEAD_MSG if method_called?(body_node, :head) && find_block(body_node, :head) problem BOTTLE_MSG if method_called?(body_node, :bottle) && find_block(body_node, :bottle) return if method_called?(body_node, :head) || find_block(body_node, :head) problem STABLE_MSG if stable_block end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/bottle.rb
Library/Homebrew/rubocops/bottle.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits the `bottle` block in formulae. class BottleFormat < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) bottle_node = find_block(formula_nodes.body_node, :bottle) return if bottle_node.nil? sha256_nodes = find_method_calls_by_name(bottle_node.body, :sha256) cellar_node = find_node_method_by_name(bottle_node.body, :cellar) cellar_source = cellar_node&.first_argument&.source if sha256_nodes.present? && cellar_node.present? offending_node(cellar_node) problem "`cellar` should be a parameter to `sha256`" do |corrector| corrector.remove(range_by_whole_lines(cellar_node.source_range, include_final_newline: true)) end end sha256_nodes.each do |sha256_node| sha256_hash = sha256_node.last_argument sha256_pairs = sha256_hash.pairs next if sha256_pairs.count != 1 sha256_pair = sha256_pairs.first sha256_key = sha256_pair.key sha256_value = sha256_pair.value next unless sha256_value.sym_type? tag = sha256_value.value digest_source = sha256_key.source sha256_line = if cellar_source.present? "sha256 cellar: #{cellar_source}, #{tag}: #{digest_source}" else "sha256 #{tag}: #{digest_source}" end offending_node(sha256_node) problem "`sha256` should use new syntax" do |corrector| corrector.replace(sha256_node.source_range, sha256_line) end end end end # This cop audits the indentation of the bottle tags in the `bottle` block in formulae. class BottleTagIndentation < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) bottle_node = find_block(formula_nodes.body_node, :bottle) return if bottle_node.nil? sha256_nodes = find_method_calls_by_name(bottle_node.body, :sha256) max_tag_column = 0 sha256_nodes.each do |sha256_node| sha256_hash = sha256_node.last_argument tag_column = T.let(sha256_hash.pairs.last.source_range.column, Integer) max_tag_column = tag_column if tag_column > max_tag_column end # This must be in a separate loop to make sure max_tag_column is truly the maximum sha256_nodes.each do |sha256_node| # rubocop:disable Style/CombinableLoops sha256_hash = sha256_node.last_argument hash = sha256_hash.pairs.last tag_column = hash.source_range.column next if tag_column == max_tag_column offending_node(hash) problem "Align bottle tags" do |corrector| new_line = (" " * (max_tag_column - tag_column)) + hash.source corrector.replace(hash.source_range, new_line) end end end end # This cop audits the indentation of the sha256 digests in the`bottle` block in formulae. class BottleDigestIndentation < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) bottle_node = find_block(formula_nodes.body_node, :bottle) return if bottle_node.nil? sha256_nodes = find_method_calls_by_name(bottle_node.body, :sha256) max_digest_column = 0 sha256_nodes.each do |sha256_node| sha256_hash = sha256_node.last_argument digest_column = T.let(sha256_hash.pairs.last.value.source_range.column, Integer) max_digest_column = digest_column if digest_column > max_digest_column end # This must be in a separate loop to make sure max_digest_column is truly the maximum sha256_nodes.each do |sha256_node| # rubocop:disable Style/CombinableLoops sha256_hash = sha256_node.last_argument hash = sha256_hash.pairs.last.value digest_column = hash.source_range.column next if digest_column == max_digest_column offending_node(hash) problem "Align bottle digests" do |corrector| new_line = (" " * (max_digest_column - digest_column)) + hash.source corrector.replace(hash.source_range, new_line) end end end end # This cop audits the order of the `bottle` block in formulae. class BottleOrder < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) bottle_node = find_block(formula_nodes.body_node, :bottle) return if bottle_node.nil? return if bottle_node.child_nodes.blank? non_sha256_nodes = [] sha256_nodes = [] bottle_block_method_calls = if bottle_node.child_nodes.last.begin_type? bottle_node.child_nodes.last.child_nodes else [bottle_node.child_nodes.last] end bottle_block_method_calls.each do |node| if node.method_name == :sha256 sha256_nodes << node else non_sha256_nodes << node end end arm64_macos_nodes = [] intel_macos_nodes = [] arm64_linux_nodes = [] intel_linux_nodes = [] sha256_nodes.each do |node| version = sha256_bottle_tag node if version == :arm64_linux arm64_linux_nodes << node elsif version.to_s.start_with?("arm64") arm64_macos_nodes << node elsif version.to_s.end_with?("_linux") intel_linux_nodes << node else intel_macos_nodes << node end end sorted_nodes = arm64_macos_nodes + intel_macos_nodes + arm64_linux_nodes + intel_linux_nodes return if sha256_order(sha256_nodes) == sha256_order(sorted_nodes) offending_node(bottle_node) problem "ARM bottles should be listed before Intel bottles" do |corrector| lines = ["bottle do"] lines += non_sha256_nodes.map { |node| " #{node.source}" } lines += arm64_macos_nodes.map { |node| " #{node.source}" } lines += intel_macos_nodes.map { |node| " #{node.source}" } lines += arm64_linux_nodes.map { |node| " #{node.source}" } lines += intel_linux_nodes.map { |node| " #{node.source}" } lines << " end" corrector.replace(bottle_node.source_range, lines.join("\n")) end end sig { params(nodes: T::Array[RuboCop::AST::SendNode]).returns(T::Array[T.any(String, Symbol)]) } def sha256_order(nodes) nodes.map do |node| sha256_bottle_tag node end end sig { params(node: AST::SendNode).returns(T.any(String, Symbol)) } def sha256_bottle_tag(node) hash_pair = node.last_argument.pairs.last if hash_pair.key.sym_type? hash_pair.key.value else hash_pair.value.value 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/rubocops/class.rb
Library/Homebrew/rubocops/class.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop makes sure that {Formula} is used as superclass. class ClassName < FormulaCop extend AutoCorrector DEPRECATED_CLASSES = %w[ GithubGistFormula ScriptFileFormula AmazonWebServicesFormula ].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) parent_class_node = formula_nodes.parent_class_node parent_class = class_name(parent_class_node) return unless DEPRECATED_CLASSES.include?(parent_class) problem "`#{parent_class}` is deprecated, use `Formula` instead" do |corrector| corrector.replace(parent_class_node.source_range, "Formula") end end end # This cop makes sure that a `test` block contains a proper test. class Test < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) test = find_block(formula_nodes.body_node, :test) return unless test if test.body.nil? problem "`test do` should not be empty" return end problem "`test do` should contain a real test" if test.body.single_line? && test.body.source.to_s == "true" test_calls(test) do |node, params| p1, p2 = params if (match = string_content(p1).match(%r{(/usr/local/(s?bin))})) offending_node(p1) problem "Use `\#{#{match[2]}}` instead of `#{match[1]}` in `#{node}`" do |corrector| corrector.replace(p1.source_range, p1.source.sub(match[1], "\#{#{match[2]}}")) end end if node == :shell_output && node_equals?(p2, 0) offending_node(p2) problem "Passing 0 to `shell_output` is redundant" do |corrector| corrector.remove(range_with_surrounding_comma(range_with_surrounding_space(range: p2.source_range, side: :left))) end end end end def_node_search :test_calls, <<~EOS (send nil? ${:system :shell_output :pipe_output} $...) EOS end end module FormulaAuditStrict # This cop makes sure that a `test` block exists. class TestPresent < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node return if find_block(body_node, :test) return if find_node_method_by_name(body_node, :disable!) offending_node(formula_nodes.class_node) if body_node.nil? problem "A `test do` test block should be added" 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/rubocops/present.rb
Library/Homebrew/rubocops/present.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # Checks for code that can be simplified using `Object#present?`. # # ### Example # # ```ruby # # bad # !foo.nil? && !foo.empty? # # # bad # foo != nil && !foo.empty? # # # good # foo.present? # ``` class Present < Base extend AutoCorrector MSG = "Use `%<prefer>s` instead of `%<current>s`." def_node_matcher :exists_and_not_empty?, <<~PATTERN (and { (send (send $_ :nil?) :!) (send (send $_ :!) :!) (send $_ :!= nil) $_ } { (send (send $_ :empty?) :!) } ) PATTERN sig { params(node: RuboCop::AST::AndNode).void } def on_and(node) exists_and_not_empty?(node) do |var1, var2| return if var1 != var2 message = format(MSG, prefer: replacement(var1), current: node.source) add_offense(node, message:) do |corrector| autocorrect(corrector, node) end end end sig { params(node: RuboCop::AST::OrNode).void } def on_or(node) exists_and_not_empty?(node) do |var1, var2| return if var1 != var2 add_offense(node, message: MSG) do |corrector| autocorrect(corrector, node) end end end sig { params(corrector: RuboCop::Cop::Corrector, node: RuboCop::AST::Node).void } def autocorrect(corrector, node) variable1, _variable2 = exists_and_not_empty?(node) range = node.source_range corrector.replace(range, replacement(variable1)) end private sig { params(node: T.nilable(RuboCop::AST::Node)).returns(String) } def replacement(node) node.respond_to?(:source) ? "#{node&.source}.present?" : "present?" end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/homepage.rb
Library/Homebrew/rubocops/homepage.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" require "rubocops/shared/homepage_helper" module RuboCop module Cop module FormulaAudit # This cop audits the `homepage` URL in formulae. class Homepage < FormulaCop include HomepageHelper extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node homepage_node = find_node_method_by_name(body_node, :homepage) if homepage_node.nil? offending_node(formula_nodes.class_node) if body_node.nil? problem "Formula should have a homepage." return end homepage_parameter_node = parameters(homepage_node).first offending_node(homepage_parameter_node) content = string_content(homepage_parameter_node) audit_homepage(:formula, content, homepage_node, homepage_parameter_node) 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/rubocops/no_fileutils_rmrf.rb
Library/Homebrew/rubocops/no_fileutils_rmrf.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `{FileUtils,instance}.rmtree` # and recommends the safer versions. class NoFileutilsRmrf < Base extend AutoCorrector MSG = "Use `rm` or `rm_r` instead of `rm_rf`, `rm_f`, or `rmtree`." def_node_matcher :any_receiver_rm_r_f?, <<~PATTERN (send {(const {nil? cbase} :FileUtils) (self)} {:rm_rf :rm_f} ...) PATTERN def_node_matcher :no_receiver_rm_r_f?, <<~PATTERN (send nil? {:rm_rf :rm_f} ...) PATTERN def_node_matcher :no_receiver_rmtree?, <<~PATTERN (send nil? :rmtree ...) PATTERN def_node_matcher :any_receiver_rmtree?, <<~PATTERN (send !nil? :rmtree ...) PATTERN sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return if neither_rm_rf_nor_rmtree?(node) add_offense(node) do |corrector| class_name = "FileUtils." if any_receiver_rm_r_f?(node) || any_receiver_rmtree?(node) new_method = if node.method?(:rm_rf) || node.method?(:rmtree) "rm_r" else "rm" end args = if any_receiver_rmtree?(node) node.receiver&.source || node.arguments.first&.source else node.arguments.first.source end args = "(#{args})" unless args.start_with?("(") corrector.replace(node.loc.expression, "#{class_name}#{new_method}#{args}") end end sig { params(node: RuboCop::AST::SendNode).returns(T::Boolean) } def neither_rm_rf_nor_rmtree?(node) !any_receiver_rm_r_f?(node) && !no_receiver_rm_r_f?(node) && !any_receiver_rmtree?(node) && !no_receiver_rmtree?(node) 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/rubocops/no_autobump.rb
Library/Homebrew/rubocops/no_autobump.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" require "rubocops/shared/no_autobump_helper" module RuboCop module Cop module FormulaAudit # This cop audits `no_autobump!` reason. # See the {NoAutobumpHelper} module for details of the checks. class NoAutobump < FormulaCop include NoAutobumpHelper extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node no_autobump_call = find_node_method_by_name(body_node, :no_autobump!) return if no_autobump_call.nil? reason_found = T.let(false, T::Boolean) reason(no_autobump_call) do |reason_node| reason_found = true offending_node(reason_node) audit_no_autobump(:formula, reason_node) end return if reason_found problem 'Add a reason for exclusion from autobump: `no_autobump! because: "..."`' end def_node_search :reason, <<~EOS (pair (sym :because) ${str sym}) 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/rubocops/service.rb
Library/Homebrew/rubocops/service.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits the service block. class Service < FormulaCop extend AutoCorrector CELLAR_PATH_AUDIT_CORRECTIONS = T.let( { bin: :opt_bin, libexec: :opt_libexec, pkgshare: :opt_pkgshare, prefix: :opt_prefix, sbin: :opt_sbin, share: :opt_share, }.freeze, T::Hash[Symbol, Symbol], ) # At least one of these methods must be defined in a service block. REQUIRED_METHOD_CALLS = [:run, :name].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) service_node = find_block(formula_nodes.body_node, :service) return if service_node.blank? method_calls = service_node.each_descendant(:send).group_by(&:method_name) method_calls.delete(:service) # NOTE: Solving the first problem here might solve the second one too # so we don't show both of them at the same time. if !method_calls.keys.intersect?(REQUIRED_METHOD_CALLS) offending_node(service_node) problem "Service blocks require `run` or `name` to be defined." elsif !method_calls.key?(:run) other_method_calls = method_calls.keys - [:name, :require_root] if other_method_calls.any? offending_node(service_node) problem "`run` must be defined to use methods other than `name` like #{other_method_calls}." end end # This check ensures that Cellar paths like `bin` are not referenced # because their `opt_` variants are more portable and work with the API. CELLAR_PATH_AUDIT_CORRECTIONS.each do |path, opt_path| next unless method_calls.key?(path) method_calls.fetch(path).each do |node| offending_node(node) problem "Use `#{opt_path}` instead of `#{path}` in service blocks." do |corrector| corrector.replace(node.source_range, opt_path) end end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/uses_from_macos.rb
Library/Homebrew/rubocops/uses_from_macos.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits formulae that are keg-only because they are provided by macos. class ProvidedByMacos < FormulaCop PROVIDED_BY_MACOS_FORMULAE = %w[ apr bc bc-gh berkeley-db bison bzip2 cups curl cyrus-sasl dyld-headers ed expat file-formula flex gperf icu4c krb5 libarchive libedit libffi libiconv libpcap libressl libxcrypt libxml2 libxslt llvm lsof m4 ncompress ncurses net-snmp netcat openldap pax pcsc-lite pod2man ruby sqlite ssh-copy-id swift tcl-tk unifdef unzip whois zip zlib ].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? find_method_with_args(body_node, :keg_only, :provided_by_macos) do return if PROVIDED_BY_MACOS_FORMULAE.include? @formula_name problem "Formulae that are `keg_only :provided_by_macos` should be " \ "added to the `PROVIDED_BY_MACOS_FORMULAE` list (in the Homebrew/brew repository)" end end end # This cop audits `uses_from_macos` dependencies in formulae. class UsesFromMacos < FormulaCop # These formulae aren't `keg_only :provided_by_macos` but are provided by # macOS (or very similarly, e.g. OpenSSL where system provides LibreSSL). # TODO: consider making some of these keg-only. ALLOWED_USES_FROM_MACOS_DEPS = %w[ bash cpio expect git groff gzip jq less mandoc openssl perl php python rsync vim xz zsh ].freeze sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? depends_on_linux = depends_on?(:linux) find_method_with_args(body_node, :uses_from_macos, /^"(.+)"/).each do |method| @offensive_node = method problem "`uses_from_macos` should not be used when Linux is required." if depends_on_linux dep = if parameters(method).first.instance_of?(RuboCop::AST::StrNode) parameters(method).first elsif parameters(method).first.instance_of?(RuboCop::AST::HashNode) parameters(method).first.keys.first end dep_name = string_content(dep) next if ALLOWED_USES_FROM_MACOS_DEPS.include? dep_name next if ProvidedByMacos::PROVIDED_BY_MACOS_FORMULAE.include? dep_name problem "`uses_from_macos` should only be used for macOS dependencies, not '#{dep_name}'." end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/dependency_order.rb
Library/Homebrew/rubocops/dependency_order.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop checks for correct order of `depends_on` in formulae. # # precedence order: # build-time > test > normal > recommended > optional class DependencyOrder < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) body_node = formula_nodes.body_node check_dependency_nodes_order(body_node) check_uses_from_macos_nodes_order(body_node) ([:head, :stable] + on_system_methods).each do |block_name| block = find_block(body_node, block_name) next unless block check_dependency_nodes_order(block.body) check_uses_from_macos_nodes_order(block.body) end end def check_uses_from_macos_nodes_order(parent_node) return if parent_node.nil? dependency_nodes = parent_node.each_child_node.select { |x| uses_from_macos_node?(x) } ensure_dependency_order(dependency_nodes) end def check_dependency_nodes_order(parent_node) return if parent_node.nil? dependency_nodes = parent_node.each_child_node.select { |x| depends_on_node?(x) } ensure_dependency_order(dependency_nodes) end def ensure_dependency_order(nodes) ordered = nodes.sort_by { |node| dependency_name(node).downcase } ordered = sort_dependencies_by_type(ordered) sort_conditional_dependencies!(ordered) verify_order_in_source(ordered) end # Separate dependencies according to precedence order: # build-time > test > normal > recommended > optional def sort_dependencies_by_type(dependency_nodes) unsorted_deps = dependency_nodes.to_a ordered = [] ordered.concat(unsorted_deps.select { |dep| buildtime_dependency? dep }) unsorted_deps -= ordered ordered.concat(unsorted_deps.select { |dep| test_dependency? dep }) unsorted_deps -= ordered ordered.concat(unsorted_deps.reject { |dep| negate_normal_dependency? dep }) unsorted_deps -= ordered ordered.concat(unsorted_deps.select { |dep| recommended_dependency? dep }) unsorted_deps -= ordered ordered.concat(unsorted_deps.select { |dep| optional_dependency? dep }) end # `depends_on :apple if build.with? "foo"` should always be defined # after `depends_on :foo`. # This method reorders the dependencies array according to the above rule. sig { params(ordered: T::Array[RuboCop::AST::Node]).returns(T::Array[RuboCop::AST::Node]) } def sort_conditional_dependencies!(ordered) length = ordered.size idx = 0 while idx < length idx1 = T.let(nil, T.nilable(Integer)) idx2 = T.let(nil, T.nilable(Integer)) ordered.each_with_index do |dep, pos| idx = pos+1 match_nodes = build_with_dependency_name(dep) next if match_nodes.blank? idx1 = pos ordered.drop(idx1+1).each_with_index do |dep2, pos2| next unless match_nodes.index(dependency_name(dep2)) idx2 = pos2 if idx2.nil? || pos2 > idx2 end break if idx2 end insert_after!(ordered, idx1, idx2 + T.must(idx1)) if idx2 end ordered end # Verify actual order of sorted `depends_on` nodes in source code; # raise RuboCop problem otherwise. def verify_order_in_source(ordered) ordered.each_with_index do |node_1, idx| l1 = line_number(node_1) l2 = T.let(nil, T.nilable(Integer)) node_2 = T.let(nil, T.nilable(RuboCop::AST::Node)) ordered.drop(idx + 1).each do |test_node| l2 = line_number(test_node) node_2 = test_node if l2 < l1 end next unless node_2 offending_node(node_1) problem "`dependency \"#{dependency_name(node_1)}\"` (line #{l1}) should be put before " \ "`dependency \"#{dependency_name(node_2)}\"` (line #{l2})" do |corrector| indentation = " " * (start_column(node_2) - line_start_column(node_2)) line_breaks = "\n" corrector.insert_before(node_2.source_range, node_1.source + line_breaks + indentation) corrector.remove(range_with_surrounding_space(range: node_1.source_range, side: :left)) end end end # Node pattern method to match # `depends_on` variants. def_node_matcher :depends_on_node?, <<~EOS {(if _ (send nil? :depends_on ...) nil?) (send nil? :depends_on ...)} EOS def_node_matcher :uses_from_macos_node?, <<~EOS {(if _ (send nil? :uses_from_macos ...) nil?) (send nil? :uses_from_macos ...)} EOS def_node_search :buildtime_dependency?, "(sym :build)" def_node_search :recommended_dependency?, "(sym :recommended)" def_node_search :test_dependency?, "(sym :test)" def_node_search :optional_dependency?, "(sym :optional)" def_node_search :negate_normal_dependency?, "(sym {:build :recommended :test :optional})" # Node pattern method to extract `name` in `depends_on :name` or `uses_from_macos :name` def_node_search :dependency_name_node, <<~EOS {(send nil? {:depends_on :uses_from_macos} {(hash (pair $_ _) ...) $({str sym} _) $(const nil? _)} ...) (if _ (send nil? :depends_on {(hash (pair $_ _)) $({str sym} _) $(const nil? _)}) nil?)} EOS # Node pattern method to extract `name` in `build.with? :name` def_node_search :build_with_dependency_node, <<~EOS (send (send nil? :build) :with? $({str sym} _)) EOS def insert_after!(arr, idx1, idx2) arr.insert(idx2+1, arr.delete_at(idx1)) end def build_with_dependency_name(node) match_nodes = build_with_dependency_node(node) match_nodes = match_nodes.to_a.compact match_nodes.map { |n| string_content(n) } unless match_nodes.empty? end def dependency_name(dependency_node) match_node = dependency_name_node(dependency_node).to_a.first string_content(match_node) if match_node 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/rubocops/components_order.rb
Library/Homebrew/rubocops/components_order.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "ast_constants" require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop checks for correct order of components in formulae. # # - `component_precedence_list` has component hierarchy in a nested list # where each sub array contains components' details which are at same precedence level class ComponentsOrder < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? @present_components, @offensive_nodes = check_order(FORMULA_COMPONENT_PRECEDENCE_LIST, body_node) component_problem @offensive_nodes[0], @offensive_nodes[1] if @offensive_nodes component_precedence_list = [ [{ name: :depends_on, type: :method_call }], [{ name: :resource, type: :block_call }], [{ name: :patch, type: :method_call }, { name: :patch, type: :block_call }], ] head_blocks = find_blocks(body_node, :head) head_blocks.each do |head_block| check_block_component_order(FORMULA_COMPONENT_PRECEDENCE_LIST, head_block) end on_system_methods.each do |on_method| on_method_blocks = find_blocks(body_node, on_method) next if on_method_blocks.empty? if on_method_blocks.length > 1 @offensive_node = on_method_blocks.second problem "There can only be one `#{on_method}` block in a formula." end check_on_system_block_content(component_precedence_list, on_method_blocks.first) end resource_blocks = find_blocks(body_node, :resource) resource_blocks.each do |resource_block| check_block_component_order(FORMULA_COMPONENT_PRECEDENCE_LIST, resource_block) on_system_blocks = {} on_system_methods.each do |on_method| on_system_blocks[on_method] = find_blocks(resource_block.body, on_method) end if on_system_blocks.empty? # Found nothing. Try without .body as depending on the code, # on_{system} might be in .body or not ... on_system_methods.each do |on_method| on_system_blocks[on_method] = find_blocks(resource_block, on_method) end end next if on_system_blocks.empty? @offensive_node = resource_block on_system_bodies = T.let([], T::Array[[RuboCop::AST::BlockNode, RuboCop::AST::Node]]) on_system_blocks.each_value do |blocks| blocks.each do |on_system_block| on_system_body = on_system_block.body branches = on_system_body.if_type? ? on_system_body.branches : [on_system_body] on_system_bodies += branches.map { |branch| [on_system_block, branch] } end end message = T.let(nil, T.nilable(String)) allowed_methods = [ [:url, :sha256], [:url, :mirror, :sha256], [:url, :version, :sha256], [:url, :mirror, :version, :sha256], ] minimum_methods = allowed_methods.first.map { |m| "`#{m}`" }.to_sentence maximum_methods = allowed_methods.last.map { |m| "`#{m}`" }.to_sentence on_system_bodies.each do |on_system_block, on_system_body| method_name = on_system_block.method_name child_nodes = on_system_body.begin_type? ? on_system_body.child_nodes : [on_system_body] if child_nodes.all? { |n| n.send_type? || n.block_type? || n.lvasgn_type? } method_names = child_nodes.filter_map do |node| next if node.lvasgn_type? next if node.method_name == :patch next if on_system_methods.include? node.method_name node.method_name end next if method_names.empty? || allowed_methods.include?(method_names) end offending_node(on_system_block) message = "`#{method_name}` blocks within `resource` blocks must contain at least " \ "#{minimum_methods} and at most #{maximum_methods} (in order)." break end if message problem message next end on_system_blocks.each do |on_method, blocks| if blocks.length > 1 problem "There can only be one `#{on_method}` block in a resource block." next end end end end def check_block_component_order(component_precedence_list, block) @present_components, offensive_node = check_order(component_precedence_list, block.body) component_problem(*offensive_node) if offensive_node end def check_on_system_block_content(component_precedence_list, on_system_block) if on_system_block.body.block_type? && !on_system_methods.include?(on_system_block.body.method_name) && on_system_block.body.method_name != :fails_with offending_node(on_system_block) problem "Nest `#{on_system_block.method_name}` blocks inside `#{on_system_block.body.method_name}` " \ "blocks when there is only one inner block." do |corrector| original_source = on_system_block.source.split("\n") new_source = [original_source.second, original_source.first, *original_source.drop(2)] corrector.replace(on_system_block.source_range, new_source.join("\n")) end end on_system_allowed_methods = %w[ livecheck keg_only disable! deprecate! depends_on conflicts_with fails_with resource patch pour_bottle? ] on_system_allowed_methods += on_system_methods.map(&:to_s) _, offensive_node = check_order(component_precedence_list, on_system_block.body) component_problem(*offensive_node) if offensive_node child_nodes = on_system_block.body.begin_type? ? on_system_block.body.child_nodes : [on_system_block.body] child_nodes.each do |child| valid_node = depends_on_node?(child) # Check for RuboCop::AST::SendNode and RuboCop::AST::BlockNode instances # only, as we are checking the method_name for `patch`, `resource`, etc. method_type = child.send_type? || child.block_type? next unless method_type valid_node ||= on_system_allowed_methods.include? child.method_name.to_s @offensive_node = child next if valid_node problem "`#{on_system_block.method_name}` cannot include `#{child.method_name}`. " \ "Only #{on_system_allowed_methods.map { |m| "`#{m}`" }.to_sentence} are allowed." end end # Reorder two nodes in the source, using the corrector instance in autocorrect method. # Components of same type are grouped together when rewriting the source. # Linebreaks are introduced if components are of two different methods/blocks/multilines. def reorder_components(corrector, node1, node2) # order_idx : node1's index in component_precedence_list # curr_p_idx: node1's index in preceding_comp_arr # preceding_comp_arr: array containing components of same type order_idx, curr_p_idx, preceding_comp_arr = get_state(node1) # curr_p_idx.positive? means node1 needs to be grouped with its own kind if curr_p_idx.positive? node2 = preceding_comp_arr[curr_p_idx - 1] indentation = " " * (start_column(node2) - line_start_column(node2)) line_breaks = node2.multiline? ? "\n\n" : "\n" corrector.insert_after(node2.source_range, line_breaks + indentation + node1.source) else indentation = " " * (start_column(node2) - line_start_column(node2)) # No line breaks up to version_scheme, order_idx == 8 line_breaks = (order_idx > 8) ? "\n\n" : "\n" corrector.insert_before(node2.source_range, node1.source + line_breaks + indentation) end corrector.remove(range_with_surrounding_space(range: node1.source_range, side: :left)) end # Returns precedence index and component's index to properly reorder and group during autocorrect. def get_state(node1) @present_components.each_with_index do |comp, idx| return [idx, comp.index(node1), comp] if comp.member?(node1) end end def check_order(component_precedence_list, body_node) present_components = component_precedence_list.map do |components| components.flat_map do |component| case component[:type] when :method_call find_method_calls_by_name(body_node, component[:name]).to_a when :block_call find_blocks(body_node, component[:name]).to_a when :method_definition find_method_def(body_node, component[:name]) end end.compact end # Check if each present_components is above rest of the present_components offensive_nodes = T.let(nil, T.nilable(T::Array[RuboCop::AST::Node])) present_components.take(present_components.size - 1).each_with_index do |preceding_component, p_idx| next if preceding_component.empty? present_components.drop(p_idx + 1).each do |succeeding_component| next if succeeding_component.empty? offensive_nodes = check_precedence(preceding_component, succeeding_component) return [present_components, offensive_nodes] if offensive_nodes end end nil end # Method to report and correct component precedence violations. def component_problem(component1, component2) return if tap_style_exception? :components_order_exceptions problem "`#{format_component(component1)}` (line #{line_number(component1)}) " \ "should be put before `#{format_component(component2)}` " \ "(line #{line_number(component2)})" do |corrector| reorder_components(corrector, component1, component2) end end # Node pattern method to match # `depends_on` variants. def_node_matcher :depends_on_node?, <<~EOS {(if _ (send nil? :depends_on ...) nil?) (send nil? :depends_on ...)} 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/rubocops/shell_command_stub.rb
Library/Homebrew/rubocops/shell_command_stub.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew class ShellCommandStub < Base MSG = "Shell command stubs must have a `.sh` counterpart." RESTRICT_ON_SEND = [:include].freeze sig { params(node: AST::SendNode).void } def on_send(node) return if node.first_argument&.const_name != "ShellCommand" stub_path = Pathname.new(processed_source.file_path) sh_cmd_path = Pathname.new("#{stub_path.dirname}/#{stub_path.basename(".rb")}.sh") return if sh_cmd_path.exist? add_offense(node) 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/rubocops/patches.rb
Library/Homebrew/rubocops/patches.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits `patch`es in formulae. class Patches < FormulaCop extend AutoCorrector sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) node = formula_nodes.node @full_source_content = T.let(source_buffer(node).source, T.nilable(String)) return if (body_node = formula_nodes.body_node).nil? external_patches = find_all_blocks(body_node, :patch) external_patches.each do |patch_block| url_node = find_every_method_call_by_name(patch_block, :url).first url_string = parameters(url_node).first sha256_node = find_every_method_call_by_name(patch_block, :sha256).first sha256_string = parameters(sha256_node).first if sha256_node patch_problems(url_string, sha256_string) end inline_patches = find_every_method_call_by_name(body_node, :patch) inline_patches.each { |patch| inline_patch_problems(patch) } if inline_patches.empty? && patch_end? offending_patch_end_node(node) add_offense(@offense_source_range, message: "Patch is missing `patch :DATA`") end patches_node = find_method_def(body_node, :patches) return if patches_node.nil? legacy_patches = find_strings(patches_node) problem "Use the `patch` DSL instead of defining a `patches` method" legacy_patches.each { |p| patch_problems(p, nil) } end private sig { params(patch_url_node: RuboCop::AST::Node, sha256_node: T.nilable(RuboCop::AST::Node)).void } def patch_problems(patch_url_node, sha256_node) patch_url = string_content(patch_url_node) if regex_match_group(patch_url_node, %r{https://github.com/[^/]*/[^/]*/pull}) problem "Use a commit hash URL rather than an unstable pull request URL: #{patch_url}" end if regex_match_group(patch_url_node, %r{.*gitlab.*/merge_request.*}) problem "Use a commit hash URL rather than an unstable merge request URL: #{patch_url}" end if regex_match_group(patch_url_node, %r{https://github.com/[^/]*/[^/]*/commit/[a-fA-F0-9]*\.diff}) problem "GitHub patches should end with .patch, not .diff: #{patch_url}" do |corrector| # Replace .diff with .patch, keeping either the closing quote or query parameter start correct = patch_url_node.source.sub(/\.diff(["?])/, '.patch\1') corrector.replace(patch_url_node.source_range, correct) corrector.replace(sha256_node.source_range, '""') if sha256_node end end bitbucket_regex = %r{bitbucket\.org/([^/]+)/([^/]+)/commits/([a-f0-9]+)/raw}i if regex_match_group(patch_url_node, bitbucket_regex) owner, repo, commit = patch_url_node.source.match(bitbucket_regex).captures correct_url = "https://api.bitbucket.org/2.0/repositories/#{owner}/#{repo}/diff/#{commit}" problem "Bitbucket patches should use the API URL: #{correct_url}" do |corrector| corrector.replace(patch_url_node.source_range, %Q("#{correct_url}")) corrector.replace(sha256_node.source_range, '""') if sha256_node end end # Only .diff passes `--full-index` to `git diff` and there is no documented way # to get .patch to behave the same for GitLab. if regex_match_group(patch_url_node, %r{.*gitlab.*/commit/[a-fA-F0-9]*\.patch}) problem "GitLab patches should end with .diff, not .patch: #{patch_url}" do |corrector| # Replace .patch with .diff, keeping either the closing quote or query parameter start correct = patch_url_node.source.sub(/\.patch(["?])/, '.diff\1') corrector.replace(patch_url_node.source_range, correct) corrector.replace(sha256_node.source_range, '""') if sha256_node end end gh_patch_param_pattern = %r{https?://github\.com/.+/.+/(?:commit|pull)/[a-fA-F0-9]*.(?:patch|diff)} if regex_match_group(patch_url_node, gh_patch_param_pattern) && !patch_url.match?(/\?full_index=\w+$/) problem "GitHub patches should use the full_index parameter: #{patch_url}?full_index=1" do |corrector| correct = patch_url_node.source.sub(/"$/, '?full_index=1"') corrector.replace(patch_url_node.source_range, correct) corrector.replace(sha256_node.source_range, '""') if sha256_node end end gh_patch_patterns = Regexp.union([%r{/raw\.github\.com/}, %r{/raw\.githubusercontent\.com/}, %r{gist\.github\.com/raw}, %r{gist\.github\.com/.+/raw}, %r{gist\.githubusercontent\.com/.+/raw}]) if regex_match_group(patch_url_node, gh_patch_patterns) && !patch_url.match?(%r{/[a-fA-F0-9]{6,40}/}) problem "GitHub/Gist patches should specify a revision: #{patch_url}" end gh_patch_diff_pattern = %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)} if regex_match_group(patch_url_node, gh_patch_diff_pattern) problem "Use a commit hash URL rather than patch-diff: #{patch_url}" end if regex_match_group(patch_url_node, %r{macports/trunk}) problem "MacPorts patches should specify a revision instead of trunk: #{patch_url}" end if regex_match_group(patch_url_node, %r{^http://trac\.macports\.org}) problem "Patches from MacPorts Trac should be https://, not http: #{patch_url}" do |corrector| corrector.replace(patch_url_node.source_range, patch_url_node.source.sub(%r{\A"http://}, '"https://')) end end return unless regex_match_group(patch_url_node, %r{^http://bugs\.debian\.org}) problem "Patches from Debian should be https://, not http: #{patch_url}" do |corrector| corrector.replace(patch_url_node.source_range, patch_url_node.source.sub(%r{\A"http://}, '"https://')) end end sig { params(patch: RuboCop::AST::Node).void } def inline_patch_problems(patch) return if !patch_data?(patch) || patch_end? offending_node(patch) problem "Patch is missing `__END__`" end def_node_search :patch_data?, <<~AST (send nil? :patch (:sym :DATA)) AST sig { returns(T::Boolean) } def patch_end? /^__END__$/.match?(@full_source_content) end sig { params(node: RuboCop::AST::Node).void } def offending_patch_end_node(node) @offensive_node = T.let(node, T.nilable(RuboCop::AST::Node)) @source_buf = T.let(source_buffer(node), T.nilable(Parser::Source::Buffer)) @line_no = T.let(node.loc.last_line + 1, T.nilable(Integer)) @column = T.let(0, T.nilable(Integer)) @length = T.let(7, T.nilable(Integer)) # "__END__".size @offense_source_range = T.let( source_range(@source_buf, @line_no, @column, @length), T.nilable(Parser::Source::Range), ) 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/rubocops/resource_requires_dependencies.rb
Library/Homebrew/rubocops/resource_requires_dependencies.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits Python formulae that include certain resources # to ensure that they also have the correct `uses_from_macos` # dependencies. class ResourceRequiresDependencies < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? resource_nodes = find_every_method_call_by_name(body_node, :resource) return if resource_nodes.empty? %w[lxml pyyaml].each do |resource_name| found = resource_nodes.find { |node| node.arguments&.first&.str_content == resource_name } next unless found uses_from_macos_nodes = find_every_method_call_by_name(body_node, :uses_from_macos) depends_on_nodes = find_every_method_call_by_name(body_node, :depends_on) uses_from_macos_or_depends_on = (uses_from_macos_nodes + depends_on_nodes).filter_map do |node| if (dep = node.arguments.first).hash_type? dep_types = dep.values.first dep_types = dep_types.array_type? ? dep_types.values : [dep_types] dep.keys.first.str_content if dep_types.select(&:sym_type?).map(&:value).include?(:build) else dep.str_content end end required_deps = case resource_name when "lxml" kind = depends_on?(:linux) ? "depends_on" : "uses_from_macos" ["libxml2", "libxslt"] when "pyyaml" kind = "depends_on" ["libyaml"] else [] end next if required_deps.all? { |dep| uses_from_macos_or_depends_on.include?(dep) } offending_node(found) problem "Add `#{kind}` lines above for #{required_deps.map { |req| "`\"#{req}\"`" }.join(" and ")}." 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/rubocops/urls.rb
Library/Homebrew/rubocops/urls.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" require "rubocops/shared/url_helper" module RuboCop module Cop module FormulaAudit # This cop audits `url`s and `mirror`s in formulae. class Urls < FormulaCop include UrlHelper sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? urls = find_every_func_call_by_name(body_node, :url) mirrors = find_every_func_call_by_name(body_node, :mirror) # Identify livecheck URLs, to skip some checks for them livecheck_url = if (livecheck = find_every_func_call_by_name(body_node, :livecheck).first) && (livecheck_url = find_every_func_call_by_name(livecheck.parent, :url).first) string_content(parameters(livecheck_url).first) end audit_url(:formula, urls, mirrors, livecheck_url:) return if formula_tap != "homebrew-core" # Check for binary URLs audit_urls(urls, /(darwin|macos|osx)/i) do |match, url| next if T.must(@formula_name).include?(match.to_s.downcase) next if url.match?(/.(patch|diff)(\?full_index=1)?$/) next if tap_style_exception? :not_a_binary_url_prefix_allowlist next if tap_style_exception? :binary_bootstrap_formula_urls_allowlist problem "#{url} looks like a binary package, not a source archive; " \ "homebrew/core is source-only." end end end # This cop makes sure that the correct format for PyPI URLs is used. class PyPiUrls < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? urls = find_every_func_call_by_name(body_node, :url) mirrors = find_every_func_call_by_name(body_node, :mirror) urls += mirrors # Check pypi URLs pypi_pattern = %r{^https?://pypi\.python\.org/} audit_urls(urls, pypi_pattern) do |_, url| problem "Use the \"Source\" URL found on the PyPI downloads page (#{get_pypi_url(url)})" end # Require long files.pythonhosted.org URLs pythonhosted_pattern = %r{^https?://files\.pythonhosted\.org/packages/source/} audit_urls(urls, pythonhosted_pattern) do |_, url| problem "Use the \"Source\" URL found on the PyPI downloads page (#{get_pypi_url(url)})" end end sig { params(url: String).returns(String) } def get_pypi_url(url) package_file = File.basename(url) package_name = T.must(package_file.match(/^(.+)-[a-z0-9.]+$/))[1] "https://pypi.org/project/#{package_name}/#files" end end # This cop makes sure that git URLs have a `revision`. class GitUrls < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? return if formula_tap != "homebrew-core" find_method_calls_by_name(body_node, :url).each do |url| next unless string_content(parameters(url).first).match?(/\.git$/) next if url_has_revision?(parameters(url).last) offending_node(url) problem "Formulae in homebrew/core should specify a revision for Git URLs" end end def_node_matcher :url_has_revision?, <<~EOS (hash <(pair (sym :revision) str) ...>) EOS end end module FormulaAuditStrict # This cop makes sure that git URLs have a `tag`. class GitUrls < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if (body_node = formula_nodes.body_node).nil? return if formula_tap != "homebrew-core" find_method_calls_by_name(body_node, :url).each do |url| next unless string_content(parameters(url).first).match?(/\.git$/) next if url_has_tag?(parameters(url).last) offending_node(url) problem "Formulae in homebrew/core should specify a tag for Git URLs" end end def_node_matcher :url_has_tag?, <<~EOS (hash <(pair (sym :tag) str) ...>) 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/rubocops/compact_blank.rb
Library/Homebrew/rubocops/compact_blank.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Homebrew # Checks if collection can be blank-compacted with `compact_blank`. # # NOTE: It is unsafe by default because false positives may occur in the # blank check of block arguments to the receiver object. # # For example, `[[1, 2], [3, nil]].reject { |first, second| second.blank? }` and # `[[1, 2], [3, nil]].compact_blank` are not compatible. The same is true for `blank?`. # This will work fine when the receiver is a hash object. # # And `compact_blank!` has different implementations for `Array`, `Hash` and # `ActionController::Parameters`. # `Array#compact_blank!`, `Hash#compact_blank!` are equivalent to `delete_if(&:blank?)`. # `ActionController::Parameters#compact_blank!` is equivalent to `reject!(&:blank?)`. # If the cop makes a mistake, autocorrected code may get unexpected behavior. # # ### Examples # # ```ruby # # bad # collection.reject(&:blank?) # collection.reject { |_k, v| v.blank? } # # # good # collection.compact_blank # ``` # # ```ruby # # bad # collection.delete_if(&:blank?) # Same behavior as `Array#compact_blank!` and `Hash#compact_blank!` # collection.delete_if { |_, v| v.blank? } # Same behavior as `Array#compact_blank!` and `Hash#compact_blank!` # collection.reject!(&:blank?) # Same behavior as `ActionController::Parameters#compact_blank!` # collection.reject! { |_k, v| v.blank? } # Same behavior as `ActionController::Parameters#compact_blank!` # # # good # collection.compact_blank! # ``` class CompactBlank < Base include RangeHelp extend AutoCorrector MSG = "Use `%<preferred_method>s` instead." RESTRICT_ON_SEND = [:reject, :delete_if, :reject!].freeze def_node_matcher :reject_with_block?, <<~PATTERN (block (send _ {:reject :delete_if :reject!}) $(args ...) (send $(lvar _) :blank?)) PATTERN def_node_matcher :reject_with_block_pass?, <<~PATTERN (send _ {:reject :delete_if :reject!} (block_pass (sym :blank?))) PATTERN sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return unless bad_method?(node) range = offense_range(node) preferred_method = preferred_method(node) add_offense(range, message: format(MSG, preferred_method:)) do |corrector| corrector.replace(range, preferred_method) end end private sig { params(node: RuboCop::AST::SendNode).returns(T::Boolean) } def bad_method?(node) return true if reject_with_block_pass?(node) if (arguments, receiver_in_block = reject_with_block?(node.parent)) return use_single_value_block_argument?(arguments, receiver_in_block) || use_hash_value_block_argument?(arguments, receiver_in_block) end false end sig { params(arguments: RuboCop::AST::ArgsNode, receiver_in_block: RuboCop::AST::Node).returns(T::Boolean) } def use_single_value_block_argument?(arguments, receiver_in_block) arguments.length == 1 && arguments.fetch(0).source == receiver_in_block.source end sig { params(arguments: RuboCop::AST::ArgsNode, receiver_in_block: RuboCop::AST::Node).returns(T::Boolean) } def use_hash_value_block_argument?(arguments, receiver_in_block) arguments.length == 2 && arguments.fetch(1).source == receiver_in_block.source end sig { params(node: RuboCop::AST::SendNode).returns(Parser::Source::Range) } def offense_range(node) end_pos = if node.parent&.block_type? && node.parent&.send_node == node node.parent.source_range.end_pos else node.source_range.end_pos end range_between(node.loc.selector.begin_pos, end_pos) end sig { params(node: RuboCop::AST::SendNode).returns(String) } def preferred_method(node) node.method?(:reject) ? "compact_blank" : "compact_blank!" 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/rubocops/rubocop-cask.rb
Library/Homebrew/rubocops/rubocop-cask.rb
# typed: strict # frozen_string_literal: true require "rubocop" require_relative "cask/constants/stanza" require_relative "cask/ast/stanza" require_relative "cask/ast/cask_header" require_relative "cask/ast/cask_block" require_relative "cask/extend/node" require_relative "cask/mixin/cask_help" require_relative "cask/mixin/on_homepage_stanza" require_relative "cask/mixin/on_url_stanza" require_relative "cask/array_alphabetization" require_relative "cask/desc" require_relative "cask/discontinued" require_relative "cask/homepage_url_styling" require_relative "cask/no_autobump" require_relative "cask/no_overrides" require_relative "cask/on_system_conditionals" require_relative "cask/shared_filelist_glob" require_relative "cask/stanza_order" require_relative "cask/stanza_grouping" require_relative "cask/uninstall_methods_order" require_relative "cask/url" require_relative "cask/url_legacy_comma_separators" require_relative "cask/variables" require_relative "cask/deprecate_disable_unsigned_reason"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/zero_zero_zero_zero.rb
Library/Homebrew/rubocops/zero_zero_zero_zero.rb
# typed: strict # frozen_string_literal: true require "rubocops/extend/formula_cop" module RuboCop module Cop module FormulaAudit # This cop audits the use of 0.0.0.0 in formulae. # 0.0.0.0 should not be used outside of test do blocks as it can be a security risk. class ZeroZeroZeroZero < FormulaCop sig { override.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes) return if formula_tap != "homebrew-core" body_node = formula_nodes.body_node return if body_node.nil? test_block = find_block(body_node, :test) # Find all string literals in the formula body_node.each_descendant(:str) do |str_node| content = string_content(str_node) next unless content.include?("0.0.0.0") next if test_block && str_node.ancestors.any?(test_block) next if valid_ip_range?(content) offending_node(str_node) problem "Do not use 0.0.0.0 as it can be a security risk." end end private sig { params(content: String).returns(T::Boolean) } def valid_ip_range?(content) # Allow private IP ranges like 10.0.0.0, 172.16.0.0-172.31.255.255, 192.168.0.0-192.168.255.255 return true if content.match?(/\b(?:10|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\.\d+\.\d+\b/) # Allow IP range notation like 0.0.0.0-255.255.255.255 return true if content.match?(/\b0\.0\.0\.0\s*-\s*255\.255\.255\.255\b/) false end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/all.rb
Library/Homebrew/rubocops/all.rb
# typed: strict # frozen_string_literal: true require_relative "../extend/array" require_relative "../extend/blank" require_relative "blank" require_relative "compact_blank" require_relative "disable_comment" require_relative "extend/mutable_constant_exclude_unfreezable" require_relative "io_read" require_relative "move_to_extend_os" require_relative "negate_include" require_relative "no_fileutils_rmrf" require_relative "presence" require_relative "present" require_relative "safe_navigation_with_blank" require_relative "shell_command_stub" require_relative "shell_commands" require_relative "install_bundler_gems" # formula audit cops require_relative "bottle" require_relative "caveats" require_relative "checksum" require_relative "class" require_relative "components_order" require_relative "components_redundancy" require_relative "conflicts" require_relative "dependency_order" require_relative "deprecate_disable" require_relative "no_autobump" require_relative "desc" require_relative "files" require_relative "homepage" require_relative "keg_only" require_relative "lines" require_relative "livecheck" require_relative "options" require_relative "patches" require_relative "resource_requires_dependencies" require_relative "service" require_relative "text" require_relative "urls" require_relative "uses_from_macos" require_relative "version" require_relative "zero_zero_zero_zero" require_relative "rubocop-cask"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/cask/deprecate_disable_unsigned_reason.rb
Library/Homebrew/rubocops/cask/deprecate_disable_unsigned_reason.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # This cop checks for use of `because: :unsigned` in `deprecate!`/`disable!` # and replaces it with the preferred `:fails_gatekeeper_check` reason. # # Example # # bad # deprecate! date: "2024-01-01", because: :unsigned # disable! because: :unsigned # # # good # deprecate! date: "2024-01-01", because: :fails_gatekeeper_check # disable! because: :fails_gatekeeper_check class DeprecateDisableUnsignedReason < Base include CaskHelp extend AutoCorrector STANZAS_TO_CHECK = [:deprecate!, :disable!].freeze MESSAGE = "Use `:fails_gatekeeper_check` instead of `:unsigned` for deprecate!/disable! reason." sig { override.params(stanza_block: RuboCop::Cask::AST::StanzaBlock).void } def on_cask_stanza_block(stanza_block) stanzas = stanza_block.stanzas.select { |s| STANZAS_TO_CHECK.include?(s.stanza_name) } stanzas.each do |stanza| stanza_node = T.cast(stanza.stanza_node, RuboCop::AST::SendNode) hash_node = stanza_node.last_argument next unless hash_node&.hash_type? # find `because: :unsigned` pairs T.cast(hash_node, RuboCop::AST::HashNode).each_pair do |key_node, value_node| next if !key_node.sym_type? || key_node.value != :because next if !value_node.sym_type? || value_node.value != :unsigned add_offense(value_node, message: MESSAGE) do |corrector| corrector.replace(value_node.source_range, ":fails_gatekeeper_check") end end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/cask/desc.rb
Library/Homebrew/rubocops/cask/desc.rb
# typed: strict # frozen_string_literal: true require "rubocops/cask/mixin/on_desc_stanza" require "rubocops/shared/desc_helper" module RuboCop module Cop module Cask # This cop audits `desc` in casks. # See the {DescHelper} module for details of the checks. class Desc < Base include OnDescStanza include DescHelper extend AutoCorrector sig { params(stanza: RuboCop::Cask::AST::Stanza).void } def on_desc_stanza(stanza) @name = T.let(cask_block&.header&.cask_token, T.nilable(String)) desc_call = stanza.stanza_node audit_desc(:cask, @name, desc_call) 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/rubocops/cask/uninstall_methods_order.rb
Library/Homebrew/rubocops/cask/uninstall_methods_order.rb
# typed: strict # frozen_string_literal: true require "rubocops/shared/helper_functions" module RuboCop module Cop module Cask # This cop checks for the correct order of methods within the # 'uninstall' and 'zap' stanzas and validates related metadata. class UninstallMethodsOrder < Base extend AutoCorrector include HelperFunctions MSG = T.let("`%<method>s` method out of order", String) # These keys are ignored when checking method order. # Mirrors AbstractUninstall::METADATA_KEYS. METADATA_KEYS = T.let( [:on_upgrade].freeze, T::Array[Symbol], ) USELESS_METADATA_MSG = T.let( "`on_upgrade` has no effect without matching `uninstall quit:` or `uninstall signal:` directives", String, ) PARTIAL_METADATA_MSG = T.let( "`on_upgrade` lists %<symbols>s without matching `uninstall` directives", String, ) sig { params(node: AST::SendNode).void } def on_send(node) return unless [:zap, :uninstall].include?(node.method_name) hash_node = node.arguments.first return if hash_node.nil? || (!hash_node.is_a?(AST::Node) && !hash_node.hash_type?) comments = processed_source.comments check_ordering(hash_node, comments) check_metadata(hash_node, comments) end private sig { params( hash_node: AST::HashNode, comments: T::Array[Parser::Source::Comment], ).void } def check_ordering(hash_node, comments) method_nodes = hash_node.pairs.map(&:key).reject do |method| name = method.children.first METADATA_KEYS.include?(name) end expected_order = method_nodes.sort_by { |method| method_order_index(method) } method_nodes.each_with_index do |method, index| next if method == expected_order[index] report_and_correct_ordering_offense(method, hash_node, expected_order, comments) end end sig { params(method: AST::Node, hash_node: AST::HashNode, expected_order: T::Array[AST::Node], comments: T::Array[Parser::Source::Comment]).void } def report_and_correct_ordering_offense(method, hash_node, expected_order, comments) add_offense(method, message: format(MSG, method: method.children.first)) do |corrector| ordered_pairs = expected_order.map do |expected_method| hash_node.pairs.find { |pair| pair.key == expected_method } end indentation = " " * (start_column(method) - line_start_column(method)) new_code = build_uninstall_body(ordered_pairs, comments, indentation) corrector.replace(hash_node.source_range, new_code) end end sig { params( hash_node: AST::HashNode, comments: T::Array[Parser::Source::Comment], ).void } def check_metadata(hash_node, comments) on_upgrade_pair = hash_node.pairs.find { |p| p.key.value == :on_upgrade } return unless on_upgrade_pair requested = on_upgrade_symbols(on_upgrade_pair.value) return report_fully_invalid_metadata(on_upgrade_pair) if requested.empty? available = [] available << :quit if hash_node.pairs.any? { |p| p.key.value == :quit } available << :signal if hash_node.pairs.any? { |p| p.key.value == :signal } valid_syms = requested & available invalid_syms = requested - available if valid_syms.empty? remaining_pairs = hash_node.pairs.reject { |p| p == on_upgrade_pair } report_and_correct_useless_metadata(hash_node, on_upgrade_pair, remaining_pairs, comments) elsif invalid_syms.any? report_partially_invalid_metadata(on_upgrade_pair.value, invalid_syms) end end sig { params(on_upgrade_pair: AST::PairNode).void } def report_fully_invalid_metadata(on_upgrade_pair) add_offense(on_upgrade_pair.value, message: "`on_upgrade` value must be :quit, :signal, or an array of those symbols") end sig { params( hash_node: AST::HashNode, on_upgrade_pair: AST::PairNode, remaining_pairs: T::Array[AST::PairNode], comments: T::Array[Parser::Source::Comment], ).void } def report_and_correct_useless_metadata( hash_node, on_upgrade_pair, remaining_pairs, comments ) if remaining_pairs.empty? # Only on_upgrade is present: report but do not attempt autocorrect # to avoid generating an empty uninstall hash or removing the stanza. add_offense(on_upgrade_pair.key, message: USELESS_METADATA_MSG) return end add_offense(on_upgrade_pair.key, message: USELESS_METADATA_MSG) do |corrector| first_pair = T.must(remaining_pairs.first) indentation = " " * (start_column(first_pair.key) - line_start_column(first_pair.key)) new_code = build_uninstall_body(remaining_pairs, comments, indentation) corrector.replace(hash_node.source_range, new_code) end end sig { params(value_node: AST::Node, invalid_syms: T::Array[Symbol]).void } def report_partially_invalid_metadata(value_node, invalid_syms) symbols_str = invalid_syms.map { |s| ":#{s}" }.join(", ") add_offense(value_node, message: format(PARTIAL_METADATA_MSG, symbols: symbols_str)) end sig { params( pairs: T::Array[AST::PairNode], comments: T::Array[Parser::Source::Comment], indentation: String, ).returns(String) } def build_uninstall_body(pairs, comments, indentation) pairs.map do |pair| source = pair.source # Find and attach a comment on the same line as the pair, if any inline_comment = comments.find do |comment| comment.location.line == pair.loc.line && comment.location.column > pair.loc.column end inline_comment ? "#{source} #{inline_comment.text}" : source end.join(",\n#{indentation}") end sig { params(value_node: AST::Node).returns(T::Array[Symbol]) } def on_upgrade_symbols(value_node) if value_node.sym_type? [T.cast(value_node, AST::SymbolNode).value] elsif value_node.array_type? value_node.children.select(&:sym_type?).map do |child| T.cast(child, AST::SymbolNode).value end else [] end end sig { params(method_node: AST::SymbolNode).returns(Integer) } def method_order_index(method_node) method_name = method_node.children.first RuboCop::Cask::Constants::UNINSTALL_METHODS_ORDER.index(method_name) || -1 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/rubocops/cask/shared_filelist_glob.rb
Library/Homebrew/rubocops/cask/shared_filelist_glob.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask class SharedFilelistGlob < Base extend AutoCorrector sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return if node.method_name != :zap node.each_descendant(:pair).each do |pair| symbols = pair.children.select(&:sym_type?).map(&:value) next unless symbols.include?(:trash) pair.each_descendant(:array).each do |array| regex = /\.sfl\d"$/ message = "Use a glob (*) instead of a specific version (ie. sfl2) for trashing Shared File List paths" array.children.each do |item| next unless item.source.match?(regex) corrected_item = item.source.sub(/sfl\d"$/, "sfl*\"") add_offense(item, message:) do |corrector| corrector.replace(item, corrected_item) end end end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/cask/variables.rb
Library/Homebrew/rubocops/cask/variables.rb
# typed: strict # frozen_string_literal: true require "forwardable" module RuboCop module Cop module Cask # This cop audits variables in casks. # # ### Example # # ```ruby # # bad # cask do # arch = Hardware::CPU.intel? ? "darwin" : "darwin-arm64" # end # # # good # cask 'foo' do # arch arm: "darwin-arm64", intel: "darwin" # end # ``` class Variables < Base extend Forwardable extend AutoCorrector include CaskHelp sig { override.params(cask_block: RuboCop::Cask::AST::CaskBlock).void } def on_cask(cask_block) @cask_block = T.let(cask_block, T.nilable(RuboCop::Cask::AST::CaskBlock)) add_offenses end private def_delegator :@cask_block, :cask_node sig { void } def add_offenses variable_assignment(cask_node) do |node, var_name, arch_condition, true_node, false_node| arm_node, intel_node = if arch_condition == :arm? [true_node, false_node] else [false_node, true_node] end replacement_string = if var_name == :arch "arch " else "#{var_name} = on_arch_conditional " end replacement_parameters = [] replacement_parameters << "arm: #{arm_node.source}" unless blank_node?(arm_node) replacement_parameters << "intel: #{intel_node.source}" unless blank_node?(intel_node) replacement_string += replacement_parameters.join(", ") add_offense(node, message: "Use `#{replacement_string}` instead of `#{node.source}`.") do |corrector| corrector.replace(node, replacement_string) end end end sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def blank_node?(node) case node.type when :str node.str_content.empty? when :nil true else false end end def_node_search :variable_assignment, <<~PATTERN $(lvasgn $_ (if (send (const (const nil? :Hardware) :CPU) ${:arm? :intel?}) $_ $_)) PATTERN 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/rubocops/cask/homepage_url_styling.rb
Library/Homebrew/rubocops/cask/homepage_url_styling.rb
# typed: strict # frozen_string_literal: true require "forwardable" require "uri" require "rubocops/shared/homepage_helper" module RuboCop module Cop module Cask # This cop audits the `homepage` URL in casks. class HomepageUrlStyling < Base include OnHomepageStanza include HelperFunctions include HomepageHelper extend AutoCorrector MSG_NO_SLASH = "'%<url>s' must have a slash after the domain." sig { params(stanza: RuboCop::Cask::AST::Stanza).void } def on_homepage_stanza(stanza) @name = T.let(cask_block&.header&.cask_token, T.nilable(String)) desc_call = T.cast(stanza.stanza_node, RuboCop::AST::SendNode) url_node = desc_call.first_argument url = if url_node.dstr_type? # Remove quotes from interpolated string. url_node.source[1..-2] else url_node.str_content end audit_homepage(:cask, url, desc_call, url_node) return unless url&.match?(%r{^.+://[^/]+$}) domain = URI(string_content(url_node, strip_dynamic: true)).host return if domain.blank? # This also takes URLs like 'https://example.org?path' # and 'https://example.org#path' into account. corrected_source = url_node.source.sub("://#{domain}", "://#{domain}/") add_offense(url_node.loc.expression, message: format(MSG_NO_SLASH, url:)) do |corrector| corrector.replace(url_node.source_range, corrected_source) 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/rubocops/cask/url_legacy_comma_separators.rb
Library/Homebrew/rubocops/cask/url_legacy_comma_separators.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # This cop checks for `version.before_comma` and `version.after_comma`. class UrlLegacyCommaSeparators < Url include OnUrlStanza extend AutoCorrector MSG_CSV = "Use `version.csv.first` instead of `version.before_comma` " \ "and `version.csv.second` instead of `version.after_comma`." sig { override.params(stanza: RuboCop::Cask::AST::Stanza).void } def on_url_stanza(stanza) return if stanza.stanza_node.block_type? url_node = T.cast(stanza.stanza_node, RuboCop::AST::SendNode).first_argument legacy_comma_separator_pattern = /version\.(before|after)_comma/ url = url_node.source return unless url.match?(legacy_comma_separator_pattern) corrected_url = url.sub("before_comma", "csv.first")&.sub("after_comma", "csv.second") add_offense(url_node.loc.expression, message: format(MSG_CSV, url:)) do |corrector| corrector.replace(url_node.source_range, corrected_url) 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/rubocops/cask/stanza_order.rb
Library/Homebrew/rubocops/cask/stanza_order.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "forwardable" module RuboCop module Cop module Cask # This cop checks that a cask's stanzas are ordered correctly, including nested within `on_*` blocks. # @see https://docs.brew.sh/Cask-Cookbook#stanza-order class StanzaOrder < Base include IgnoredNode extend AutoCorrector include CaskHelp MESSAGE = "`%<stanza>s` stanza out of order" def on_cask_stanza_block(stanza_block) stanzas = stanza_block.stanzas ordered_stanzas = sort_stanzas(stanzas) return if stanzas == ordered_stanzas stanzas.zip(ordered_stanzas).each do |stanza_before, stanza_after| next if stanza_before == stanza_after add_offense( stanza_before.method_node, message: format(MESSAGE, stanza: stanza_before.stanza_name), ) do |corrector| next if part_of_ignored_node?(stanza_before.method_node) corrector.replace( stanza_before.source_range_with_comments, stanza_after.source_with_comments, ) # Ignore node so that nested content is not auto-corrected and clobbered. ignore_node(stanza_before.method_node) end end end def on_new_investigation super ignored_nodes.clear end private def sort_stanzas(stanzas) stanzas.sort do |stanza1, stanza2| i1 = stanza1.stanza_index i2 = stanza2.stanza_index if i1 == i2 i1 = stanzas.index(stanza1) i2 = stanzas.index(stanza2) end i1 - i2 end end def stanza_order_index(stanza) stanza_name = stanza.respond_to?(:method_name) ? stanza.method_name : stanza.stanza_name RuboCop::Cask::Constants::STANZA_ORDER.index(stanza_name) end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/cask/url.rb
Library/Homebrew/rubocops/cask/url.rb
# typed: strict # frozen_string_literal: true require "rubocops/shared/url_helper" module RuboCop module Cop module Cask # This cop checks that a cask's `url` stanza is formatted correctly. # # ### Example # # ```ruby # # bad # url "https://example.com/download/foo.dmg", # verified: "https://example.com/download" # # # good # url "https://example.com/download/foo.dmg", # verified: "example.com/download/" # ``` class Url < Base extend AutoCorrector include OnUrlStanza include UrlHelper sig { params(stanza: RuboCop::Cask::AST::Stanza).void } def on_url_stanza(stanza) if stanza.stanza_node.block_type? if cask_tap == "homebrew-cask" add_offense(stanza.stanza_node, message: 'Do not use `url "..." do` blocks in Homebrew/homebrew-cask.') end return end stanza_node = T.cast(stanza.stanza_node, RuboCop::AST::SendNode) url_stanza = stanza_node.first_argument hash_node = stanza_node.last_argument audit_url(:cask, [stanza.stanza_node], [], livecheck_url: false) return unless hash_node.hash_type? unless stanza_node.source.match?(/",\n *\w+:/) add_offense( stanza_node.source_range, message: "Keyword URL parameter should be on a new indented line.", ) do |corrector| corrector.replace(stanza_node.source_range, stanza_node.source.gsub(/",\s*/, "\",\n ")) end end hash_node.each_pair do |key_node, value_node| next if key_node.source != "verified" next unless value_node.str_type? if value_node.source.start_with?(%r{^"https?://}) add_offense( value_node.source_range, message: "Verified URL parameter value should not contain a URL scheme.", ) do |corrector| corrector.replace(value_node.source_range, value_node.source.gsub(%r{^"https?://}, "\"")) end end # Skip if the URL and the verified value are the same. next if value_node.source == url_stanza.source.gsub(%r{^"https?://}, "\"") # Skip if the URL has two path components, e.g. `https://github.com/google/fonts.git`. next if url_stanza.source.gsub(%r{^"https?://}, "\"").count("/") == 2 # Skip if the verified value ends with a slash. next if value_node.str_content.end_with?("/") add_offense( value_node.source_range, message: "Verified URL parameter value should end with a /.", ) do |corrector| corrector.replace(value_node.source_range, value_node.source.gsub(/"$/, "/\"")) end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/cask/array_alphabetization.rb
Library/Homebrew/rubocops/cask/array_alphabetization.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true module RuboCop module Cop module Cask class ArrayAlphabetization < Base extend AutoCorrector sig { params(node: RuboCop::AST::SendNode).void } def on_send(node) return unless [:conflicts_with, :uninstall, :zap].include?(node.method_name) node.each_descendant(:pair).each do |pair| symbols = pair.children.select(&:sym_type?).map(&:value) next if symbols.intersect?([:signal, :script, :early_script, :args, :input]) pair.each_descendant(:array).each do |array| if array.children.length == 1 add_offense(array, message: "Avoid single-element arrays by removing the []") do |corrector| corrector.replace(array.source_range, array.children.first.source) end end next if array.children.length <= 1 sorted_array = sort_array(array.source.split("\n")).join("\n") next if array.source == sorted_array add_offense(array, message: "The array elements should be ordered alphabetically") do |corrector| corrector.replace(array.source_range, sorted_array) end end end end def sort_array(source) # Combine each comment with the line(s) below so that they remain in the same relative location combined_source = source.each_with_index.filter_map do |line, index| next if line.blank? next if line.strip.start_with?("#") next recursively_find_comments(source, index, line) end # Separate the lines into those that should be sorted and those that should not # i.e. skip the opening and closing brackets of the array. to_sort, to_keep = combined_source.partition { |line| !line.include?("[") && !line.include?("]") } # Sort the lines that should be sorted to_sort.sort! do |a, b| a_non_comment = a.split("\n").reject { |line| line.strip.start_with?("#") }.first b_non_comment = b.split("\n").reject { |line| line.strip.start_with?("#") }.first a_non_comment.downcase <=> b_non_comment.downcase end # Merge the sorted lines and the unsorted lines, preserving the original positions of the unsorted lines combined_source.map { |line| to_keep.include?(line) ? line : to_sort.shift } end def recursively_find_comments(source, index, line) if source[index - 1].strip.start_with?("#") return recursively_find_comments(source, index - 1, "#{source[index - 1]}\n#{line}") end line 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/rubocops/cask/discontinued.rb
Library/Homebrew/rubocops/cask/discontinued.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # This cop corrects `caveats { discontinued }` to `deprecate!`. class Discontinued < Base include CaskHelp extend AutoCorrector MESSAGE = "Use `deprecate!` instead of `caveats { discontinued }`." sig { override.params(stanza_block: RuboCop::Cask::AST::StanzaBlock).void } def on_cask_stanza_block(stanza_block) stanza_block.stanzas.select(&:caveats?).each do |stanza| find_discontinued_method_call(stanza.stanza_node) do |node| if caveats_contains_only_discontinued?(node.parent) add_offense(node.parent, message: MESSAGE) do |corrector| corrector.replace(node.parent.source_range, "deprecate! date: \"#{Date.today}\", because: :discontinued") end else add_offense(node, message: MESSAGE) end end end end def_node_matcher :caveats_contains_only_discontinued?, <<~EOS (block (send nil? :caveats) (args) (send nil? :discontinued)) EOS def_node_search :find_discontinued_method_call, <<~EOS $(send nil? :discontinued) 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/rubocops/cask/on_system_conditionals.rb
Library/Homebrew/rubocops/cask/on_system_conditionals.rb
# typed: strict # frozen_string_literal: true require "forwardable" require "rubocops/shared/on_system_conditionals_helper" module RuboCop module Cop module Cask # This cop makes sure that OS conditionals are consistent. # # ### Example # # ```ruby # # bad # cask 'foo' do # if MacOS.version == :tahoe # sha256 "..." # end # end # # # good # cask 'foo' do # on_tahoe do # sha256 "..." # end # end # ``` class OnSystemConditionals < Base extend Forwardable extend AutoCorrector include OnSystemConditionalsHelper include CaskHelp FLIGHT_STANZA_NAMES = [:preflight, :postflight, :uninstall_preflight, :uninstall_postflight].freeze sig { override.params(cask_block: RuboCop::Cask::AST::CaskBlock).void } def on_cask(cask_block) @cask_block = T.let(cask_block, T.nilable(RuboCop::Cask::AST::CaskBlock)) toplevel_stanzas.each do |stanza| next unless FLIGHT_STANZA_NAMES.include? stanza.stanza_name audit_on_system_blocks(stanza.stanza_node, stanza.stanza_name) end audit_arch_conditionals(cask_body, allowed_blocks: FLIGHT_STANZA_NAMES) audit_macos_version_conditionals(cask_body, recommend_on_system: false) simplify_sha256_stanzas audit_identical_sha256_across_architectures end private sig { returns(T.nilable(RuboCop::Cask::AST::CaskBlock)) } attr_reader :cask_block def_delegators :cask_block, :toplevel_stanzas, :cask_body sig { void } def simplify_sha256_stanzas nodes = {} sha256_on_arch_stanzas(cask_body) do |node, method, value| nodes[method.to_s.delete_prefix("on_").to_sym] = { node:, value: } end return if !nodes.key?(:arm) || !nodes.key?(:intel) offending_node(nodes[:arm][:node]) replacement_string = "sha256 arm: #{nodes[:arm][:value].inspect}, intel: #{nodes[:intel][:value].inspect}" problem "Use `#{replacement_string}` instead of nesting the `sha256` stanzas in " \ "`on_intel` and `on_arm` blocks" do |corrector| corrector.replace(nodes[:arm][:node].source_range, replacement_string) corrector.replace(nodes[:intel][:node].source_range, "") end end sig { void } def audit_identical_sha256_across_architectures sha256_stanzas = toplevel_stanzas.select { |stanza| stanza.stanza_name == :sha256 } sha256_stanzas.each do |stanza| sha256_node = stanza.stanza_node next if sha256_node.arguments.count != 1 next unless sha256_node.arguments.first.hash_type? hash_node = sha256_node.arguments.first arm_sha = T.let(nil, T.nilable(String)) intel_sha = T.let(nil, T.nilable(String)) hash_node.pairs.each do |pair| key = pair.key next unless key.sym_type? value = pair.value next unless value.str_type? case key.value when :arm arm_sha = value.value when :intel intel_sha = value.value end end next unless arm_sha next unless intel_sha next if arm_sha != intel_sha offending_node(sha256_node) problem "sha256 values for different architectures should not be identical." end end def_node_search :sha256_on_arch_stanzas, <<~PATTERN $(block (send nil? ${:on_intel :on_arm}) (args) (send nil? :sha256 (str $_))) PATTERN 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/rubocops/cask/no_autobump.rb
Library/Homebrew/rubocops/cask/no_autobump.rb
# typed: strict # frozen_string_literal: true require "forwardable" require "rubocops/shared/no_autobump_helper" module RuboCop module Cop module Cask # This cop audits `no_autobump!` reason. # See the {NoAutobumpHelper} module for details of the checks. class NoAutobump < Base extend Forwardable extend AutoCorrector include CaskHelp include NoAutobumpHelper sig { override.params(cask_block: RuboCop::Cask::AST::CaskBlock).void } def on_cask(cask_block) @cask_block = T.let(cask_block, T.nilable(RuboCop::Cask::AST::CaskBlock)) toplevel_stanzas.select(&:no_autobump?).each do |stanza| no_autobump_node = stanza.stanza_node reason_found = T.let(false, T::Boolean) reason(no_autobump_node) do |reason_node| reason_found = true audit_no_autobump(:cask, reason_node) end next if reason_found problem 'Add a reason for exclusion from autobump: `no_autobump! because: "..."`' end end private sig { returns(T.nilable(RuboCop::Cask::AST::CaskBlock)) } attr_reader :cask_block def_delegators :cask_block, :toplevel_stanzas def_node_search :reason, <<~EOS (pair (sym :because) ${str sym}) 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/rubocops/cask/stanza_grouping.rb
Library/Homebrew/rubocops/cask/stanza_grouping.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "forwardable" module RuboCop module Cop module Cask # This cop checks that a cask's stanzas are grouped correctly, including nested within `on_*` blocks. # @see https://docs.brew.sh/Cask-Cookbook#stanza-order class StanzaGrouping < Base extend Forwardable extend AutoCorrector include CaskHelp include RangeHelp MISSING_LINE_MSG = "stanza groups should be separated by a single empty line" EXTRA_LINE_MSG = "stanzas within the same group should have no lines between them" def on_cask(cask_block) @cask_block = cask_block @line_ops = {} cask_stanzas = cask_block.toplevel_stanzas add_offenses(cask_stanzas) return if (on_blocks = on_system_methods(cask_stanzas)).none? on_blocks.map(&:method_node).select(&:block_type?).each do |on_block| stanzas = inner_stanzas(T.cast(on_block, RuboCop::AST::BlockNode), processed_source.comments) add_offenses(stanzas) end end private attr_reader :cask_block, :line_ops def_delegators :cask_block, :cask_node, :toplevel_stanzas def add_offenses(stanzas) stanzas.each_cons(2) do |stanza, next_stanza| next unless next_stanza if missing_line_after?(stanza, next_stanza) add_offense_missing_line(stanza) elsif extra_line_after?(stanza, next_stanza) add_offense_extra_line(stanza) end end end def missing_line_after?(stanza, next_stanza) !(stanza.same_group?(next_stanza) || empty_line_after?(stanza)) end def extra_line_after?(stanza, next_stanza) stanza.same_group?(next_stanza) && empty_line_after?(stanza) end def empty_line_after?(stanza) source_line_after(stanza).empty? end def source_line_after(stanza) processed_source[index_of_line_after(stanza)] end def index_of_line_after(stanza) stanza.source_range.last_line end def add_offense_missing_line(stanza) line_index = index_of_line_after(stanza) line_ops[line_index] = :insert add_offense(line_index, message: MISSING_LINE_MSG) do |corrector| corrector.insert_before(@range, "\n") end end def add_offense_extra_line(stanza) line_index = index_of_line_after(stanza) line_ops[line_index] = :remove add_offense(line_index, message: EXTRA_LINE_MSG) do |corrector| corrector.remove(@range) end end def add_offense(line_index, message:) line_length = [processed_source[line_index].size, 1].max @range = source_range(processed_source.buffer, line_index + 1, 0, line_length) super(@range, message:) 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/rubocops/cask/no_overrides.rb
Library/Homebrew/rubocops/cask/no_overrides.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask class NoOverrides < Base include CaskHelp # These stanzas can be overridden by `on_*` blocks, so take them into account. # TODO: Update this list if new stanzas are added to `Cask::DSL` that call `set_unique_stanza`. OVERRIDABLE_METHODS = [ :appcast, :arch, :auto_updates, :conflicts_with, :container, :desc, :homepage, :os, :sha256, :url, :version ].freeze sig { override.params(cask_block: RuboCop::Cask::AST::CaskBlock).void } def on_cask(cask_block) message = "Do not use a top-level `%<stanza>s` stanza as the default. " \ "Add it to an `on_{system}` block instead. " \ "Use `:or_older` or `:or_newer` to specify a range of macOS versions." cask_stanzas = cask_block.toplevel_stanzas return if (on_blocks = on_system_methods(cask_stanzas)).none? stanzas_in_blocks = on_system_stanzas(on_blocks) cask_stanzas.each do |stanza| # Skip if the stanza is not allowed to be overridden. next unless OVERRIDABLE_METHODS.include?(stanza.stanza_name) # Skip if the stanza outside of a block is not also in an `on_*` block. next unless stanzas_in_blocks.include?(stanza.stanza_name) add_offense(stanza.source_range, message: format(message, stanza: stanza.stanza_name)) end end sig { params(on_system: T::Array[RuboCop::Cask::AST::Stanza]).returns(T::Set[Symbol]) } def on_system_stanzas(on_system) message = "Do not use a `depends_on macos:` stanza inside an `on_{system}` block. " \ "Add it once to specify the oldest macOS supported by any version in the cask." names = T.let(Set.new, T::Set[Symbol]) method_nodes = on_system.map(&:method_node) # Check if multiple `on_{system}` blocks have different `depends_on macos:` versions. # If so, this indicates architecture-specific requirements and is allowed. macos_versions = T.let([], T::Array[String]) method_nodes.select(&:block_type?).each do |node| node.child_nodes.each do |child| child.each_node(:send) do |send_node| next if send_node.method_name != :depends_on macos_pair = send_node.arguments.first.pairs.find { |a| a.key.value == :macos } macos_versions << macos_pair.value.source if macos_pair end end end # Allow if there are multiple different macOS versions specified allow_macos_depends_in_blocks = macos_versions.size > 1 && macos_versions.uniq.size > 1 method_nodes.select(&:block_type?).each do |node| node.child_nodes.each do |child| child.each_node(:send) do |send_node| # Skip (nested) `livecheck` block as its `url` is different # from a download `url`. next if send_node.method_name == :livecheck || inside_livecheck_defined?(send_node) # Skip string interpolations. if send_node.ancestors.drop_while { |a| !a.begin_type? }.any? { |a| a.dstr_type? || a.regexp_type? } next end next if RuboCop::Cask::Constants::ON_SYSTEM_METHODS.include?(send_node.method_name) if send_node.method_name == :depends_on && send_node.arguments.first.pairs.any? { |a| a.key.value == :macos } && OnSystemConditionalsHelper::ON_SYSTEM_OPTIONS.map do |m| :"on_#{m}" end.include?(T.cast(node, RuboCop::AST::BlockNode).method_name) && !allow_macos_depends_in_blocks # Allow `depends_on macos:` in multiple `on_{system}` blocks for architecture-specific requirements add_offense(send_node.source_range, message:) end names.add(send_node.method_name) end end end names end sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def inside_livecheck_defined?(node) single_stanza_livecheck_defined?(node) || multi_stanza_livecheck_defined?(node) end sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def single_stanza_livecheck_defined?(node) node.parent.block_type? && node.parent.method_name == :livecheck end sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def multi_stanza_livecheck_defined?(node) grandparent_node = node.parent.parent node.parent.begin_type? && grandparent_node.block_type? && grandparent_node.method_name == :livecheck 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/rubocops/cask/mixin/on_desc_stanza.rb
Library/Homebrew/rubocops/cask/mixin/on_desc_stanza.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # Common functionality for checking desc stanzas. module OnDescStanza extend Forwardable include CaskHelp sig { override.params(cask_block: T.nilable(RuboCop::Cask::AST::CaskBlock)).void } def on_cask(cask_block) @cask_block = T.let(cask_block, T.nilable(RuboCop::Cask::AST::CaskBlock)) toplevel_stanzas.select(&:desc?).each do |stanza| on_desc_stanza(stanza) end end private sig { returns(T.nilable(RuboCop::Cask::AST::CaskBlock)) } attr_reader :cask_block def_delegators :cask_block, :toplevel_stanzas 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/rubocops/cask/mixin/on_url_stanza.rb
Library/Homebrew/rubocops/cask/mixin/on_url_stanza.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # Common functionality for checking url stanzas. module OnUrlStanza extend Forwardable include CaskHelp sig { override.params(cask_block: T.nilable(RuboCop::Cask::AST::CaskBlock)).void } def on_cask(cask_block) @cask_block = T.let(cask_block, T.nilable(RuboCop::Cask::AST::CaskBlock)) toplevel_stanzas.select(&:url?).each do |stanza| on_url_stanza(stanza) end end private sig { returns(T.nilable(RuboCop::Cask::AST::CaskBlock)) } attr_reader :cask_block def_delegators :cask_block, :toplevel_stanzas 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/rubocops/cask/mixin/cask_help.rb
Library/Homebrew/rubocops/cask/mixin/cask_help.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # Common functionality for cops checking casks. module CaskHelp prepend CommentsHelp # Update the rbi file if changing this: https://github.com/sorbet/sorbet/issues/259 sig { overridable.params(cask_block: RuboCop::Cask::AST::CaskBlock).void } def on_cask(cask_block); end sig { overridable.params(cask_stanza_block: RuboCop::Cask::AST::StanzaBlock).void } def on_cask_stanza_block(cask_stanza_block); end sig { params(block_node: RuboCop::AST::BlockNode).void } def on_block(block_node) super if defined? super return if !block_node.cask_block? && !block_node.cask_on_system_block? comments = comments_in_range(block_node).to_a stanza_block = RuboCop::Cask::AST::StanzaBlock.new(block_node, comments) on_cask_stanza_block(stanza_block) return unless block_node.cask_block? @file_path = T.let(processed_source.file_path, T.nilable(String)) cask_block = RuboCop::Cask::AST::CaskBlock.new(block_node, comments) on_cask(cask_block) end alias on_itblock on_block sig { params( cask_stanzas: T::Array[RuboCop::Cask::AST::Stanza], ).returns( T::Array[RuboCop::Cask::AST::Stanza], ) } def on_system_methods(cask_stanzas) cask_stanzas.select(&:on_system_block?) end sig { params( block_node: RuboCop::AST::BlockNode, comments: T::Array[Parser::Source::Comment], ).returns( T::Array[RuboCop::Cask::AST::Stanza], ) } def inner_stanzas(block_node, comments) block_contents = block_node.child_nodes.select(&:begin_type?) inner_nodes = block_contents.map(&:child_nodes).flatten.select(&:send_type?) inner_nodes.map { |n| RuboCop::Cask::AST::Stanza.new(n, comments) } end sig { returns(T.nilable(String)) } def cask_tap return unless (match_obj = @file_path&.match(%r{/(homebrew-\w+)/})) match_obj[1] 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/rubocops/cask/mixin/on_homepage_stanza.rb
Library/Homebrew/rubocops/cask/mixin/on_homepage_stanza.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cop module Cask # Common functionality for checking homepage stanzas. module OnHomepageStanza extend Forwardable include CaskHelp sig { override.params(cask_block: T.nilable(RuboCop::Cask::AST::CaskBlock)).void } def on_cask(cask_block) @cask_block = T.let(cask_block, T.nilable(RuboCop::Cask::AST::CaskBlock)) toplevel_stanzas.select(&:homepage?).each do |stanza| on_homepage_stanza(stanza) end end private sig { returns(T.nilable(RuboCop::Cask::AST::CaskBlock)) } attr_reader :cask_block def_delegators :cask_block, :toplevel_stanzas 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/rubocops/cask/extend/node.rb
Library/Homebrew/rubocops/cask/extend/node.rb
# typed: strict # frozen_string_literal: true module RuboCop module AST # Extensions for RuboCop's AST Node class. class Node include RuboCop::Cask::Constants def_node_matcher :method_node, "{$(send ...) (block $(send ...) ...)}" def_node_matcher :block_body, "(block _ _ $_)" def_node_matcher :cask_block?, "(block (send nil? :cask ...) args ...)" def_node_matcher :on_system_block?, "(block (send nil? {#{ON_SYSTEM_METHODS.map(&:inspect).join(" ")}} ...) args ...)" def_node_matcher :arch_variable?, "(lvasgn _ (send nil? :on_arch_conditional ...))" def_node_matcher :begin_block?, "(begin ...)" sig { returns(T::Boolean) } def cask_on_system_block? (on_system_block? && each_ancestor.any?(&:cask_block?)) || false end sig { returns(T::Boolean) } def stanza? return true if arch_variable? case self when RuboCop::AST::BlockNode, RuboCop::AST::SendNode ON_SYSTEM_METHODS.include?(method_name) || STANZA_ORDER.include?(method_name) else false end end sig { returns(T::Boolean) } def heredoc? loc.is_a?(Parser::Source::Map::Heredoc) end sig { returns(Parser::Source::Range) } def location_expression base_expression = loc.expression descendants.select(&:heredoc?).reduce(base_expression) do |expr, node| expr.join(node.loc.heredoc_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/rubocops/cask/ast/cask_block.rb
Library/Homebrew/rubocops/cask/ast/cask_block.rb
# typed: strict # frozen_string_literal: true require "forwardable" module RuboCop module Cask module AST class StanzaBlock extend T::Helpers sig { returns(RuboCop::AST::BlockNode) } attr_reader :block_node sig { returns(T::Array[Parser::Source::Comment]) } attr_reader :comments sig { params(block_node: RuboCop::AST::BlockNode, comments: T::Array[Parser::Source::Comment]).void } def initialize(block_node, comments) @block_node = block_node @comments = comments end sig { returns(T::Array[Stanza]) } def stanzas return [] unless (block_body = block_node.block_body) # If a block only contains one stanza, it is that stanza's direct parent, otherwise # stanzas are grouped in a nested block and the block is that nested block's parent. is_stanza = if block_body.begin_block? ->(node) { node.parent.parent == block_node } else ->(node) { node.parent == block_node } end @stanzas ||= T.let( block_body.each_node .select(&:stanza?) .select(&is_stanza) .map { |node| Stanza.new(node, comments) }, T.nilable(T::Array[Stanza]), ) end end # This class wraps the AST block node that represents the entire cask # definition. It includes various helper methods to aid cops in their # analysis. class CaskBlock < StanzaBlock extend Forwardable sig { returns(RuboCop::AST::BlockNode) } def cask_node block_node end def_delegator :cask_node, :block_body, :cask_body sig { returns(CaskHeader) } def header @header ||= T.let(CaskHeader.new(block_node.method_node), T.nilable(CaskHeader)) end # TODO: Use `StanzaBlock#stanzas` for all cops, where possible. sig { returns(T::Array[Stanza]) } def stanzas return [] unless cask_body @stanzas ||= cask_body.each_node .select(&:stanza?) .map { |node| Stanza.new(node, comments) } end sig { returns(T::Array[Stanza]) } def toplevel_stanzas # If a `cask` block only contains one stanza, it is that stanza's direct parent, # otherwise stanzas are grouped in a block and `cask` is that block's parent. is_toplevel_stanza = if cask_body.begin_block? ->(stanza) { stanza.parent_node.parent.cask_block? } else ->(stanza) { stanza.parent_node.cask_block? } end @toplevel_stanzas ||= T.let(stanzas.select(&is_toplevel_stanza), T.nilable(T::Array[Stanza])) 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/rubocops/cask/ast/cask_header.rb
Library/Homebrew/rubocops/cask/ast/cask_header.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true module RuboCop module Cask module AST # This class wraps the AST method node that represents the cask header. It # includes various helper methods to aid cops in their analysis. class CaskHeader def initialize(method_node) @method_node = method_node end attr_reader :method_node def header_str @header_str ||= source_range.source end def source_range @source_range ||= method_node.loc.expression end sig { returns(String) } def preferred_header_str "cask '#{cask_token}'" end def cask_token @cask_token ||= method_node.first_argument.str_content end def hash_node @hash_node ||= method_node.each_child_node(:hash).first end def pair_node @pair_node ||= hash_node.each_child_node(:pair).first end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/cask/ast/stanza.rb
Library/Homebrew/rubocops/cask/ast/stanza.rb
# typed: strict # frozen_string_literal: true require "forwardable" module RuboCop module Cask module AST # This class wraps the AST send/block node that encapsulates the method # call that comprises the stanza. It includes various helper methods to # aid cops in their analysis. class Stanza extend Forwardable sig { params( method_node: RuboCop::AST::Node, all_comments: T::Array[T.any(String, Parser::Source::Comment)], ).void } def initialize(method_node, all_comments) @method_node = method_node @all_comments = all_comments end sig { returns(RuboCop::AST::Node) } attr_reader :method_node alias stanza_node method_node sig { returns(T::Array[T.any(Parser::Source::Comment, String)]) } attr_reader :all_comments def_delegator :stanza_node, :parent, :parent_node def_delegator :stanza_node, :arch_variable? def_delegator :stanza_node, :on_system_block? sig { returns(Parser::Source::Range) } def source_range stanza_node.location_expression end sig { returns(Parser::Source::Range) } def source_range_with_comments comments.reduce(source_range) do |range, comment| range.join(comment.loc.expression) end end def_delegator :source_range, :source def_delegator :source_range_with_comments, :source, :source_with_comments sig { returns(Symbol) } def stanza_name return :on_arch_conditional if arch_variable? return stanza_node.method_node&.method_name if stanza_node.block_type? T.cast(stanza_node, RuboCop::AST::SendNode).method_name end sig { returns(T.nilable(T::Array[Symbol])) } def stanza_group Constants::STANZA_GROUP_HASH[stanza_name] end sig { returns(T.nilable(Integer)) } def stanza_index Constants::STANZA_ORDER.index(stanza_name) end sig { params(other: Stanza).returns(T::Boolean) } def same_group?(other) stanza_group == other.stanza_group end sig { returns(T::Array[Parser::Source::Comment]) } def comments @comments ||= T.let( stanza_node.each_node.reduce([]) do |comments, node| comments | comments_hash[node.loc] end, T.nilable(T::Array[Parser::Source::Comment]), ) end sig { returns(T::Hash[Parser::Source::Map, T::Array[Parser::Source::Comment]]) } def comments_hash @comments_hash ||= T.let( Parser::Source::Comment.associate_locations(stanza_node.parent, all_comments), T.nilable(T::Hash[Parser::Source::Map, T::Array[Parser::Source::Comment]]), ) end sig { params(other: T.untyped).returns(T::Boolean) } def ==(other) self.class == other.class && stanza_node == other.stanza_node end alias eql? == Constants::STANZA_ORDER.each do |stanza_name| class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{stanza_name.to_s.chomp("!")}? # def url? stanza_name == :#{stanza_name} # stanza_name == :url end # end RUBY 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/rubocops/cask/constants/stanza.rb
Library/Homebrew/rubocops/cask/constants/stanza.rb
# typed: strict # frozen_string_literal: true module RuboCop module Cask # Constants available globally for use in all cask cops. module Constants ON_SYSTEM_METHODS = T.let( [:arm, :intel, *MacOSVersion::SYMBOLS.keys].map { |option| :"on_#{option}" }.freeze, T::Array[Symbol], ) ON_SYSTEM_METHODS_STANZA_ORDER = T.let( [ :arm, :intel, *MacOSVersion::SYMBOLS.reverse_each.to_h.keys, # Oldest OS blocks first since that's more common in Casks. ].map { |option, _| :"on_#{option}" }.freeze, T::Array[Symbol], ) STANZA_GROUPS = T.let( [ [:arch, :on_arch_conditional, :os], [:version, :sha256], ON_SYSTEM_METHODS_STANZA_ORDER, [:language], [:url, :appcast, :name, :desc, :homepage], [:livecheck], [:no_autobump!], [:deprecate!, :disable!], [ :auto_updates, :conflicts_with, :depends_on, :container, ], [ :rename, ], [ :suite, :app, :pkg, :installer, :binary, :manpage, :bash_completion, :fish_completion, :zsh_completion, :colorpicker, :dictionary, :font, :input_method, :internet_plugin, :keyboard_layout, :prefpane, :qlplugin, :mdimporter, :screen_saver, :service, :audio_unit_plugin, :vst_plugin, :vst3_plugin, :artifact, :stage_only, ], [:preflight], [:postflight], [:uninstall_preflight], [:uninstall_postflight], [:uninstall], [:zap], [:caveats], ].freeze, T::Array[T::Array[Symbol]], ) STANZA_GROUP_HASH = T.let( STANZA_GROUPS.each_with_object({}) do |stanza_group, hash| stanza_group.each { |stanza| hash[stanza] = stanza_group } end.freeze, T::Hash[Symbol, T::Array[Symbol]], ) STANZA_ORDER = T.let(STANZA_GROUPS.flatten.freeze, T::Array[Symbol]) UNINSTALL_METHODS_ORDER = [ :early_script, :launchctl, :quit, :signal, :login_item, :kext, :script, :pkgutil, :delete, :trash, :rmdir, ].freeze end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/extend/mutable_constant_exclude_unfreezable.rb
Library/Homebrew/rubocops/extend/mutable_constant_exclude_unfreezable.rb
# typed: strict # frozen_string_literal: true require "rubocop/cop/style/mutable_constant" module RuboCop module Cop module Sorbet # TODO: delete this file when https://github.com/Shopify/rubocop-sorbet/pull/256 is available module MutableConstantExcludeUnfreezable class << self sig { params(base: RuboCop::AST::NodePattern::Macros).void } def prepended(base) base.def_node_matcher(:t_let, <<~PATTERN) (send (const nil? :T) :let $_constant _type) PATTERN base.def_node_matcher(:t_type_alias?, <<~PATTERN) (block (send (const {nil? cbase} :T) :type_alias ...) ...) PATTERN base.def_node_matcher(:type_member?, <<~PATTERN) (block (send nil? :type_member ...) ...) PATTERN end end sig { params(value: RuboCop::AST::Node).void } def on_assignment(value) T.unsafe(self).t_let(value) do |constant| value = T.let(constant, RuboCop::AST::Node) end return if T.unsafe(self).t_type_alias?(value) return if T.unsafe(self).type_member?(value) super end end end end end RuboCop::Cop::Style::MutableConstant.prepend( RuboCop::Cop::Sorbet::MutableConstantExcludeUnfreezable, )
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/extend/formula_cop.rb
Library/Homebrew/rubocops/extend/formula_cop.rb
# typed: strict # frozen_string_literal: true require "rubocops/shared/helper_functions" module RuboCop module Cop # Abstract base class for all formula cops. class FormulaCop < Base extend T::Helpers include RangeHelp include HelperFunctions abstract! exclude_from_registry sig { returns(T.nilable(String)) } attr_accessor :file_path @registry = T.let(Registry.global, RuboCop::Cop::Registry) class FormulaNodes < T::Struct prop :node, RuboCop::AST::ClassNode prop :class_node, RuboCop::AST::ConstNode prop :parent_class_node, RuboCop::AST::ConstNode prop :body_node, RuboCop::AST::Node end # This method is called by RuboCop and is the main entry point. sig { params(node: RuboCop::AST::ClassNode).void } def on_class(node) @file_path = T.let(processed_source.file_path, T.nilable(String)) return unless file_path_allowed? return unless formula_class?(node) class_node, parent_class_node, body = *node @body = T.let(body, T.nilable(RuboCop::AST::Node)) @formula_name = T.let(Pathname.new(@file_path).basename(".rb").to_s, T.nilable(String)) @tap_style_exceptions = T.let(nil, T.nilable(T::Hash[Symbol, T::Array[String]])) audit_formula(FormulaNodes.new(node:, class_node:, parent_class_node:, body_node: T.must(@body))) end sig { abstract.params(formula_nodes: FormulaNodes).void } def audit_formula(formula_nodes); end # Yields to block when there is a match. # # @param urls [Array] url/mirror method call nodes # @param regex [Regexp] pattern to match URLs sig { params( urls: T::Array[RuboCop::AST::Node], regex: Regexp, _block: T.proc.params(arg0: T::Array[RuboCop::AST::Node], arg1: String, arg2: Integer).void ).void } def audit_urls(urls, regex, &_block) urls.each_with_index do |url_node, index| url_string_node = parameters(url_node).first url_string = string_content(url_string_node) match_object = regex_match_group(url_string_node, regex) next unless match_object offending_node(url_string_node.parent) yield match_object, url_string, index end end # Returns if the formula depends on dependency_name. # # @param dependency_name dependency's name sig { params(dependency_name: T.any(String, Symbol), types: Symbol).returns(T::Boolean) } def depends_on?(dependency_name, *types) return false if @body.nil? types = [:any] if types.empty? dependency_nodes = find_every_method_call_by_name(@body, :depends_on) idx = dependency_nodes.index do |n| types.any? { |type| depends_on_name_type?(n, dependency_name, type) } end return false if idx.nil? @offensive_node = T.let(dependency_nodes[idx], T.nilable(RuboCop::AST::Node)) true end # Returns true if given dependency name and dependency type exist in given dependency method call node. # TODO: Add case where key of hash is an array sig { params( node: RuboCop::AST::Node, name: T.nilable(T.any(String, Symbol)), type: Symbol, ).returns( T::Boolean, ) } def depends_on_name_type?(node, name = nil, type = :required) name_match = !name # Match only by type when name is nil case type when :required type_match = required_dependency?(node) name_match ||= required_dependency_name?(node, name) if type_match when :build, :test, :optional, :recommended type_match = dependency_type_hash_match?(node, type) name_match ||= dependency_name_hash_match?(node, name) if type_match when :any type_match = true name_match ||= required_dependency_name?(node, name) || false name_match ||= dependency_name_hash_match?(node, name) || false else type_match = false end @offensive_node = node if type_match || name_match type_match && name_match end def_node_search :required_dependency?, <<~EOS (send nil? :depends_on ({str sym} _)) EOS def_node_search :required_dependency_name?, <<~EOS (send nil? :depends_on ({str sym} %1)) EOS def_node_search :dependency_type_hash_match?, <<~EOS (hash (pair ({str sym} _) ({str sym} %1))) EOS def_node_search :dependency_name_hash_match?, <<~EOS (hash (pair ({str sym} %1) (...))) EOS # Return all the caveats' string nodes in an array. sig { returns(T::Array[RuboCop::AST::Node]) } def caveats_strings return [] if @body.nil? find_strings(find_method_def(@body, :caveats)).to_a end # Returns the sha256 str node given a sha256 call node. sig { params(call: RuboCop::AST::Node).returns(T.nilable(RuboCop::AST::Node)) } def get_checksum_node(call) return if parameters(call).empty? || parameters(call).nil? if parameters(call).first.str_type? parameters(call).first # sha256 is passed as a key-value pair in bottle blocks elsif parameters(call).first.hash_type? if parameters(call).first.keys.first.value == :cellar # sha256 :cellar :any, :tag "hexdigest" parameters(call).first.values.last elsif parameters(call).first.keys.first.is_a?(RuboCop::AST::SymbolNode) # sha256 :tag "hexdigest" parameters(call).first.values.first else # Legacy bottle block syntax # sha256 "hexdigest" => :tag parameters(call).first.keys.first end end end # Yields to a block with comment text as parameter. sig { params(_block: T.proc.params(arg0: String).void).void } def audit_comments(&_block) processed_source.comments.each do |comment_node| @offensive_node = comment_node yield comment_node.text end end # Returns true if the formula is versioned. sig { returns(T::Boolean) } def versioned_formula? return false if @formula_name.nil? @formula_name.include?("@") end # Returns the formula tap. sig { returns(T.nilable(String)) } def formula_tap return unless (match_obj = @file_path&.match(%r{/(homebrew-\w+)/})) match_obj[1] end # Returns the style exceptions directory from the file path. sig { returns(T.nilable(String)) } def style_exceptions_dir file_directory = File.dirname(@file_path) if @file_path return unless file_directory # if we're in a sharded subdirectory, look below that. directory_name = File.basename(file_directory) formula_directory = if directory_name.length == 1 || directory_name == "lib" File.dirname(file_directory) else file_directory end # if we're in a Formula or HomebrewFormula subdirectory, look below that. formula_directory_names = ["Formula", "HomebrewFormula"].freeze directory_name = File.basename(formula_directory) tap_root_directory = if formula_directory_names.include?(directory_name) File.dirname(formula_directory) else formula_directory end "#{tap_root_directory}/style_exceptions" end # Returns whether the given formula exists in the given style exception list. # Defaults to the current formula being checked. sig { params(list: Symbol, formula: T.nilable(String)).returns(T::Boolean) } def tap_style_exception?(list, formula = nil) if @tap_style_exceptions.nil? && !formula_tap.nil? @tap_style_exceptions = {} Pathname.glob("#{style_exceptions_dir}/*.json").each do |exception_file| list_name = exception_file.basename.to_s.chomp(".json").to_sym list_contents = begin JSON.parse exception_file.read rescue JSON::ParserError nil end next if list_contents.nil? || list_contents.none? @tap_style_exceptions[list_name] = list_contents end end return false if @tap_style_exceptions.nil? || @tap_style_exceptions.none? return false unless @tap_style_exceptions.key? list T.must(@tap_style_exceptions[list]).include?(formula || @formula_name) end private sig { params(node: RuboCop::AST::Node).returns(T::Boolean) } def formula_class?(node) _, class_node, = *node class_names = %w[ Formula GithubGistFormula ScriptFileFormula AmazonWebServicesFormula ] !!(class_node && class_names.include?(string_content(class_node))) end sig { returns(T::Boolean) } def file_path_allowed? return true if @file_path.nil? # file_path is nil when source is directly passed to the cop, e.g. in specs !@file_path.include?("/Library/Homebrew/test/") end sig { returns(T::Array[Symbol]) } def on_system_methods @on_system_methods ||= T.let( [:intel, :arm, :macos, :linux, :system, *MacOSVersion::SYMBOLS.keys].map do |m| :"on_#{m}" end, T.nilable(T::Array[Symbol]), ) 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/rubocops/shared/no_autobump_helper.rb
Library/Homebrew/rubocops/shared/no_autobump_helper.rb
# typed: strict # frozen_string_literal: true require "rubocops/shared/helper_functions" module RuboCop module Cop # This cop audits `no_autobump!` reason. module NoAutobumpHelper include HelperFunctions PUNCTUATION_MARKS = %w[. ! ?].freeze DISALLOWED_NO_AUTOBUMP_REASONS = %w[extract_plist latest_version].freeze sig { params(_type: Symbol, reason_node: RuboCop::AST::Node).void } def audit_no_autobump(_type, reason_node) @offensive_node = T.let(reason_node, T.nilable(RuboCop::AST::Node)) reason_string = string_content(reason_node) if reason_node.sym_type? && DISALLOWED_NO_AUTOBUMP_REASONS.include?(reason_string) problem "`:#{reason_string}` reason should not be used" end return if reason_node.sym_type? if reason_string.start_with?("it ") problem "Do not start the reason with `it`" do |corrector| corrector.replace(T.must(@offensive_node).source_range, "\"#{reason_string[3..]}\"") end end return unless PUNCTUATION_MARKS.include?(reason_string[-1]) problem "Do not end the reason with a punctuation mark" do |corrector| corrector.replace(T.must(@offensive_node).source_range, "\"#{reason_string.chop}\"") 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/rubocops/shared/desc_helper.rb
Library/Homebrew/rubocops/shared/desc_helper.rb
# typed: strict # frozen_string_literal: true require "rubocops/shared/helper_functions" module RuboCop module Cop # This module performs common checks the `desc` field in both formulae and casks. module DescHelper include HelperFunctions MAX_DESC_LENGTH = 80 VALID_LOWERCASE_WORDS = %w[ iOS iPhone macOS ].freeze sig { params(type: Symbol, name: T.nilable(String), desc_call: T.nilable(RuboCop::AST::Node)).void } def audit_desc(type, name, desc_call) # Check if a desc is present. if desc_call.nil? problem "#{type.to_s.capitalize} should have a `desc` (description)." return end @offensive_node = T.let(desc_call, T.nilable(RuboCop::AST::Node)) @name = T.let(name, T.nilable(String)) desc = T.cast(desc_call, RuboCop::AST::SendNode).first_argument # Check if the desc is empty. desc_length = string_content(desc).length if desc_length.zero? problem "The `desc` (description) should not be an empty string." return end # Check the desc for leading whitespace. desc_problem "Description shouldn't have leading spaces." if regex_match_group(desc, /^\s+/) # Check the desc for trailing whitespace. desc_problem "Description shouldn't have trailing spaces." if regex_match_group(desc, /\s+$/) # Check if "command-line" is spelled incorrectly in the desc. if (match = regex_match_group(desc, /(command ?line)/i)) c = match.to_s[0] desc_problem "Description should use \"#{c}ommand-line\" instead of \"#{match}\"." end # Check if the desc starts with an article. desc_problem "Description shouldn't start with an article." if regex_match_group(desc, /^(the|an?)(?=\s)/i) # Check if invalid lowercase words are at the start of a desc. if !VALID_LOWERCASE_WORDS.include?(string_content(desc).split.first) && regex_match_group(desc, /^[a-z]/) desc_problem "Description should start with a capital letter." end # Check if the desc starts with the formula's or cask's name. name_regex = T.must(name).delete("-").chars.join('[\s\-]?') if regex_match_group(desc, /^#{name_regex}\b/i) desc_problem "Description shouldn't start with the #{type} name." end if type == :cask && (match = regex_match_group(desc, /\b(macOS|Mac( ?OS( ?X)?)?|OS ?X)(?! virtual machines?)\b/i)) && match[1] != "MAC" add_offense(@offensive_source_range, message: "Description shouldn't contain the platform.") end # Check if a full stop is used at the end of a desc (apart from in the case of "etc."). if regex_match_group(desc, /\.$/) && !string_content(desc).end_with?("etc.") desc_problem "Description shouldn't end with a full stop." end # Check if the desc contains Unicode emojis or symbols (Unicode Other Symbols category). desc_problem "Description shouldn't contain Unicode emojis or symbols." if regex_match_group(desc, /\p{So}/) # Check if the desc length exceeds maximum length. return if desc_length <= MAX_DESC_LENGTH problem "Description is too long. It should be less than #{MAX_DESC_LENGTH} characters. " \ "The current length is #{desc_length}." end # Auto correct desc problems. `regex_match_group` must be called before this to populate @offense_source_range. sig { params(message: String).void } def desc_problem(message) add_offense(@offensive_source_range, message:) do |corrector| match_data = T.must(@offensive_node).source.match(/\A(?<quote>["'])(?<correction>.*)(?:\k<quote>)\Z/) correction = match_data[:correction] quote = match_data[:quote] next if correction.nil? correction.gsub!(/^\s+/, "") correction.gsub!(/\s+$/, "") correction.sub!(/^(the|an?)\s+/i, "") first_word = correction.split.first unless VALID_LOWERCASE_WORDS.include?(first_word) first_char = first_word.to_s[0] correction[0] = first_char.upcase if first_char end correction.gsub!(/(ommand ?line)/i, "ommand-line") correction.gsub!(/(^|[^a-z])#{@name}([^a-z]|$)/i, "\\1\\2") correction.gsub!(/\s?\p{So}/, "") correction.gsub!(/^\s+/, "") correction.gsub!(/\s+$/, "") correction.gsub!(/\.$/, "") next if correction == match_data[:correction] corrector.replace(@offensive_node&.source_range, "#{quote}#{correction}#{quote}") 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/rubocops/shared/url_helper.rb
Library/Homebrew/rubocops/shared/url_helper.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "rubocops/shared/helper_functions" module RuboCop module Cop # This module performs common checks the `homepage` field in both formulae and casks. module UrlHelper include HelperFunctions # Yields to block when there is a match. # # @param urls [Array] url/mirror method call nodes # @param regex [Regexp] pattern to match URLs def audit_urls(urls, regex) urls.each_with_index do |url_node, index| if @type == :cask url_string_node = url_node.first_argument url_string = url_node.source else url_string_node = parameters(url_node).first url_string = string_content(url_string_node) end match_object = regex_match_group(url_string_node, regex) next unless match_object offending_node(url_string_node.parent) yield match_object, url_string, index end end def audit_url(type, urls, mirrors, livecheck_url: false) @type = type # URLs must be ASCII; IDNs must be punycode ascii_pattern = /[^\p{ASCII}]+/ audit_urls(urls, ascii_pattern) do |_, url| problem "Please use the ASCII (Punycode-encoded host, URL-encoded path and query) version of #{url}." end # Prefer ftpmirror.gnu.org as suggested by https://www.gnu.org/prep/ftp.en.html gnu_pattern = %r{^(?:https?|ftp)://ftp\.gnu\.org/(.*)} audit_urls(urls, gnu_pattern) do |match, url| problem "#{url} should be: https://ftpmirror.gnu.org/gnu/#{match[1]}" end # Fossies upstream requests they aren't used as primary URLs # https://github.com/Homebrew/homebrew-core/issues/14486#issuecomment-307753234 fossies_pattern = %r{^https?://fossies\.org/} audit_urls(urls, fossies_pattern) do problem "Please don't use \"fossies.org\" in the `url` (using as a mirror is fine)" end apache_pattern = %r{^https?://(?:[^/]*\.)?apache\.org/(?:dyn/closer\.cgi\?path=/?|dist/)(.*)}i audit_urls(urls, apache_pattern) do |match, url| next if url == livecheck_url problem "#{url} should be: https://www.apache.org/dyn/closer.lua?path=#{match[1]}" end version_control_pattern = %r{^(cvs|bzr|hg|fossil)://} audit_urls(urls, version_control_pattern) do |match, _| problem "Use of the \"#{match[1]}://\" scheme is deprecated, pass `using: :#{match[1]}` instead" end svn_pattern = %r{^svn\+http://} audit_urls(urls, svn_pattern) do |_, _| problem "Use of the \"svn+http://\" scheme is deprecated, pass `using: :svn` instead" end audit_urls(mirrors, /.*/) do |_, mirror| urls.each do |url| url_string = string_content(parameters(url).first) next unless url_string.eql?(mirror) problem "URL should not be duplicated as a mirror: #{url_string}" end end urls += mirrors # Check a variety of SSL/TLS URLs that don't consistently auto-redirect # or are overly common errors that need to be reduced & fixed over time. http_to_https_patterns = Regexp.union([%r{^http://ftp\.gnu\.org/}, %r{^http://ftpmirror\.gnu\.org/}, %r{^http://download\.savannah\.gnu\.org/}, %r{^http://download-mirror\.savannah\.gnu\.org/}, %r{^http://(?:[^/]*\.)?apache\.org/}, %r{^http://code\.google\.com/}, %r{^http://fossies\.org/}, %r{^http://mirrors\.kernel\.org/}, %r{^http://mirrors\.ocf\.berkeley\.edu/}, %r{^http://(?:[^/]*\.)?bintray\.com/}, %r{^http://tools\.ietf\.org/}, %r{^http://launchpad\.net/}, %r{^http://github\.com/}, %r{^http://bitbucket\.org/}, %r{^http://anonscm\.debian\.org/}, %r{^http://cpan\.metacpan\.org/}, %r{^http://hackage\.haskell\.org/}, %r{^http://(?:[^/]*\.)?archive\.org}, %r{^http://(?:[^/]*\.)?freedesktop\.org}, %r{^http://(?:[^/]*\.)?mirrorservice\.org/}, %r{^http://downloads?\.sourceforge\.net/}]) audit_urls(urls, http_to_https_patterns) do |_, url, index| # It's fine to have a plain HTTP mirror further down the mirror list. https_url = url.dup.insert(4, "s") https_index = T.let(nil, T.nilable(Integer)) audit_urls(urls, https_url) do |_, _, found_https_index| https_index = found_https_index end problem "Please use https:// for #{url}" if !https_index || https_index > index end apache_mirror_pattern = %r{^https?://(?:[^/]*\.)?apache\.org/dyn/closer\.(?:cgi|lua)\?path=/?(.*)}i audit_urls(mirrors, apache_mirror_pattern) do |match, mirror| problem "#{mirror} should be: https://archive.apache.org/dist/#{match[1]}" end cpan_pattern = %r{^http://search\.mcpan\.org/CPAN/(.*)}i audit_urls(urls, cpan_pattern) do |match, url| problem "#{url} should be: https://cpan.metacpan.org/#{match[1]}" end gnome_pattern = %r{^(http|ftp)://ftp\.gnome\.org/pub/gnome/(.*)}i audit_urls(urls, gnome_pattern) do |match, url| problem "#{url} should be: https://download.gnome.org/#{match[2]}" end debian_pattern = %r{^git://anonscm\.debian\.org/users/(.*)}i audit_urls(urls, debian_pattern) do |match, url| problem "#{url} should be: https://anonscm.debian.org/git/users/#{match[1]}" end # Prefer HTTP/S when possible over FTP protocol due to possible firewalls. mirror_service_pattern = %r{^ftp://ftp\.mirrorservice\.org} audit_urls(urls, mirror_service_pattern) do |_, url| problem "Please use https:// for #{url}" end cpan_ftp_pattern = %r{^ftp://ftp\.cpan\.org/pub/CPAN(.*)}i audit_urls(urls, cpan_ftp_pattern) do |match_obj, url| problem "#{url} should be: http://search.cpan.org/CPAN#{match_obj[1]}" end # SourceForge url patterns sourceforge_patterns = %r{^https?://.*\b(sourceforge|sf)\.(com|net)} audit_urls(urls, sourceforge_patterns) do |_, url| # Skip if the URL looks like a SVN repository. next if url.include? "/svnroot/" next if url.include? "svn.sourceforge" next if url.include? "/p/" if url =~ /(\?|&)use_mirror=/ problem "Don't use \"#{Regexp.last_match(1)}use_mirror\" in SourceForge URLs (`url` is #{url})." end problem "Don't use \"/download\" in SourceForge URLs (`url` is #{url})." if url.end_with?("/download") if url.match?(%r{^https?://(sourceforge|sf)\.}) && url != livecheck_url problem "Use \"https://downloads.sourceforge.net\" to get geolocation (`url` is #{url})." end if url.match?(%r{^https?://prdownloads\.}) problem "Don't use \"prdownloads\" in SourceForge URLs (`url` is #{url})." end if url.match?(%r{^http://\w+\.dl\.}) problem "Don't use specific \"dl\" mirrors in SourceForge URLs (`url` is #{url})." end # sf.net does HTTPS -> HTTP redirects. if url.match?(%r{^https?://downloads?\.sf\.net}) problem "Use \"https://downloads.sourceforge.net\" instead of \"downloads.sf.net\" (`url` is #{url})" end end # Debian has an abundance of secure mirrors. Let's not pluck the insecure # one out of the grab bag. unsecure_deb_pattern = %r{^http://http\.debian\.net/debian/(.*)}i audit_urls(urls, unsecure_deb_pattern) do |match, _| problem <<~EOS Please use a secure mirror for Debian URLs. We recommend: https://deb.debian.org/debian/#{match[1]} EOS end # Check to use canonical URLs for Debian packages noncanon_deb_pattern = Regexp.union([%r{^https://mirrors\.kernel\.org/debian/}, %r{^https://mirrors\.ocf\.berkeley\.edu/debian/}, %r{^https://(?:[^/]*\.)?mirrorservice\.org/sites/ftp\.debian\.org/debian/}]) audit_urls(urls, noncanon_deb_pattern) do |_, url| problem "Please use https://deb.debian.org/debian/ for #{url}" end # Check for new-url Google Code download URLs, https:// is preferred google_code_pattern = Regexp.union([%r{^http://[A-Za-z0-9\-.]*\.googlecode\.com/files.*}, %r{^http://code\.google\.com/}]) audit_urls(urls, google_code_pattern) do |_, url| problem "Please use https:// for #{url}" end # Check for `git://` GitHub repository URLs, https:// is preferred. git_gh_pattern = %r{^git://[^/]*github\.com/} audit_urls(urls, git_gh_pattern) do |_, url| problem "Please use https:// for #{url}" end # Check for `git://` Gitorious repository URLs, https:// is preferred. git_gitorious_pattern = %r{^git://[^/]*gitorious\.org/} audit_urls(urls, git_gitorious_pattern) do |_, url| problem "Please use https:// for #{url}" end # Check for `http://` GitHub repository URLs, https:// is preferred. gh_pattern = %r{^http://github\.com/.*\.git$} audit_urls(urls, gh_pattern) do |_, url| problem "Please use https:// for #{url}" end # Check for default branch GitHub archives. if type == :formula tarball_gh_pattern = %r{^https://github\.com/.*archive/(main|master)\.(tar\.gz|zip)$} audit_urls(urls, tarball_gh_pattern) do problem "Use versioned rather than branch tarballs for stable checksums." end end # Use new-style archive downloads. archive_gh_pattern = %r{https://.*github.*/(?:tar|zip)ball/} audit_urls(urls, archive_gh_pattern) do |_, url| next if url.end_with?(".git") problem "Use /archive/ URLs for GitHub tarballs (`url` is #{url})." end archive_refs_gh_pattern = %r{https://.*github.+/archive/(?![a-fA-F0-9]{40})(?!refs/(tags|heads)/)(.*)\.tar\.gz$} audit_urls(urls, archive_refs_gh_pattern) do |match, url| next if url.end_with?(".git") problem %Q(Use "refs/tags/#{match[2]}" or "refs/heads/#{match[2]}" for GitHub references (`url` is #{url}).) end # Don't use GitHub .zip files zip_gh_pattern = %r{https://.*github.*/(archive|releases)/.*\.zip$} audit_urls(urls, zip_gh_pattern) do |_, url| next if url.match? %r{raw.githubusercontent.com/.*/.*/(main|master|HEAD)/} next if url.include?("releases/download") next if url.include?("desktop.githubusercontent.com/releases/") problem "Use GitHub tarballs rather than zipballs (`url` is #{url})." end # Don't use GitHub codeload URLs codeload_gh_pattern = %r{https?://codeload\.github\.com/(.+)/(.+)/(?:tar\.gz|zip)/(.+)} audit_urls(urls, codeload_gh_pattern) do |match, url| problem <<~EOS Use GitHub archive URLs: https://github.com/#{match[1]}/#{match[2]}/archive/#{match[3]}.tar.gz Rather than codeload: #{url} EOS end # Check for Maven Central URLs, prefer HTTPS redirector over specific host maven_pattern = %r{https?://(?:central|repo\d+)\.maven\.org/maven2/(.+)$} audit_urls(urls, maven_pattern) do |match, url| problem "#{url} should be: https://search.maven.org/remotecontent?filepath=#{match[1]}" 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/rubocops/shared/homepage_helper.rb
Library/Homebrew/rubocops/shared/homepage_helper.rb
# typed: strict # frozen_string_literal: true require "rubocops/shared/helper_functions" module RuboCop module Cop # This module performs common checks the `homepage` field in both formulae and casks. module HomepageHelper include HelperFunctions sig { params( type: Symbol, content: String, homepage_node: RuboCop::AST::Node, homepage_parameter_node: RuboCop::AST::Node ).void } def audit_homepage(type, content, homepage_node, homepage_parameter_node) @offensive_node = T.let(homepage_node, T.nilable(RuboCop::AST::Node)) problem "#{type.to_s.capitalize} should have a `homepage`." if content.empty? @offensive_node = homepage_parameter_node problem "The `homepage` should start with http or https." unless content.match?(%r{^https?://}) case content # Freedesktop is complicated to handle - It has SSL/TLS, but only on certain subdomains. # To enable https Freedesktop change the URL from http://project.freedesktop.org/wiki to # https://wiki.freedesktop.org/project_name. # "Software" is redirected to https://wiki.freedesktop.org/www/Software/project_name when %r{^http://((?:www|nice|libopenraw|liboil|telepathy|xorg)\.)?freedesktop\.org/(?:wiki/)?} if content.include?("Software") problem "Freedesktop homepages should be styled: https://wiki.freedesktop.org/www/Software/project_name" else problem "Freedesktop homepages should be styled: https://wiki.freedesktop.org/project_name" end # Google Code homepages should end in a slash when %r{^https?://code\.google\.com/p/[^/]+[^/]$} problem "Google Code homepages should end with a slash" do |corrector| corrector.replace(homepage_parameter_node.source_range, "\"#{content}/\"") end when %r{^http://([^/]*)\.(sf|sourceforge)\.net(/|$)} fixed = "https://#{Regexp.last_match(1)}.sourceforge.io/" problem "SourceForge homepages should be: #{fixed}" do |corrector| corrector.replace(homepage_parameter_node.source_range, "\"#{fixed}\"") end when /readthedocs\.org/ fixed = content.sub("readthedocs.org", "readthedocs.io") problem "Readthedocs homepages should be: #{fixed}" do |corrector| corrector.replace(homepage_parameter_node.source_range, "\"#{fixed}\"") end when %r{^https://github.com.*\.git$} problem "GitHub homepages should not end with .git" do |corrector| corrector.replace(homepage_parameter_node.source_range, "\"#{content.delete_suffix(".git")}\"") end # People will run into mixed content sometimes, but we should enforce and then add # exemptions as they are discovered. Treat mixed content on homepages as a bug. # Justify each exemptions with a code comment so we can keep track here. # # Compact the above into this list as we're able to remove detailed notations, etc over time. when # Check for `http://` GitHub homepage URLs, `https://` is preferred. # NOTE: Only check homepages that are repository pages, not `*.github.com` hosts. %r{^http://github\.com/}, %r{^http://[^/]*\.github\.io/}, # Savannah has full SSL/TLS support but no auto-redirect. # Doesn't apply to the download URLs, only the homepage. %r{^http://savannah\.nongnu\.org/}, %r{^http://[^/]*\.sourceforge\.io/}, # There's an auto-redirect here, but this mistake is incredibly common too. # Only applies to the homepage and subdomains for now, not the FTP URLs. %r{^http://((?:build|cloud|developer|download|extensions|git| glade|help|library|live|nagios|news|people| projects|rt|static|wiki|www)\.)?gnome\.org}x, %r{^http://[^/]*\.apache\.org}, %r{^http://packages\.debian\.org}, %r{^http://wiki\.freedesktop\.org/}, %r{^http://((?:www)\.)?gnupg\.org/}, %r{^http://ietf\.org}, %r{^http://[^/.]+\.ietf\.org}, %r{^http://[^/.]+\.tools\.ietf\.org}, %r{^http://www\.gnu\.org/}, %r{^http://code\.google\.com/}, %r{^http://bitbucket\.org/}, %r{^http://(?:[^/]*\.)?archive\.org} problem "Please use https:// for #{content}" do |corrector| corrector.replace(homepage_parameter_node.source_range, "\"#{content.sub("http", "https")}\"") 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/rubocops/shared/helper_functions.rb
Library/Homebrew/rubocops/shared/helper_functions.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "rubocop" require_relative "../../warnings" Warnings.ignore :parser_syntax do require "parser/current" end module RuboCop module Cop # Helper functions for cops. module HelperFunctions include RangeHelp # Checks for regex match of pattern in the node and # sets the appropriate instance variables to report the match. def regex_match_group(node, pattern) string_repr = string_content(node).encode("UTF-8", invalid: :replace) match_object = string_repr.match(pattern) return unless match_object node_begin_pos = start_column(node) line_begin_pos = line_start_column(node) @column = if node_begin_pos == line_begin_pos node_begin_pos + match_object.begin(0) - line_begin_pos else node_begin_pos + match_object.begin(0) - line_begin_pos + 1 end @length = match_object.to_s.length @line_no = line_number(node) @source_buf = source_buffer(node) @offensive_node = node @offensive_source_range = T.let( source_range(@source_buf, @line_no, @column, @length), T.nilable(Parser::Source::Range), ) match_object end # Returns the begin position of the node's line in source code. def line_start_column(node) node.source_range.source_buffer.line_range(node.loc.line).begin_pos end # Returns the begin position of the node in source code. def start_column(node) node.source_range.begin_pos end # Returns the line number of the node. sig { params(node: RuboCop::AST::Node).returns(Integer) } def line_number(node) node.loc.line end # Source buffer is required as an argument to report style violations. sig { params(node: RuboCop::AST::Node).returns(Parser::Source::Buffer) } def source_buffer(node) node.source_range.source_buffer end # Returns the string representation if node is of type str(plain) or dstr(interpolated) or const. def string_content(node, strip_dynamic: false) case node.type when :str node.str_content when :dstr content = "" node.each_child_node(:str, :begin) do |child| content += if child.begin_type? strip_dynamic ? "" : child.source else child.str_content end end content when :send if node.method?(:+) && (node.receiver.str_type? || node.receiver.dstr_type?) content = string_content(node.receiver) arg = node.arguments.first content += string_content(arg) if arg content else "" end when :const node.const_name when :sym node.children.first.to_s else "" end end def problem(msg, &block) add_offense(@offensive_node, message: msg, &block) end # Returns all string nodes among the descendants of given node. def find_strings(node) return [] if node.nil? return [node] if node.str_type? node.each_descendant(:str) end # Returns method_node matching method_name. def find_node_method_by_name(node, method_name) return if node.nil? node.each_child_node(:send) do |method_node| next if method_node.method_name != method_name @offensive_node = method_node return method_node end # If not found then, parent node becomes the offensive node @offensive_node = node.parent nil end # Gets/sets the given node as the offending node when required in custom cops. def offending_node(node = nil) return @offensive_node if node.nil? @offensive_node = node end # Returns an array of method call nodes matching method_name inside node with depth first order (child nodes). def find_method_calls_by_name(node, method_name) return if node.nil? nodes = node.each_child_node(:send).select { |method_node| method_name == method_node.method_name } # The top level node can be a method nodes << node if node.send_type? && node.method_name == method_name nodes end # Returns an array of method call nodes matching method_name in every descendant of node. # Returns every method call if no method_name is passed. def find_every_method_call_by_name(node, method_name = nil) return if node.nil? node.each_descendant(:send).select do |method_node| method_name.nil? || method_name == method_node.method_name end end # Returns array of function call nodes matching func_name in every descendant of node. # # - matches function call: `foo(*args, **kwargs)` # - does not match method calls: `foo.bar(*args, **kwargs)` # - returns every function call if no func_name is passed def find_every_func_call_by_name(node, func_name = nil) return if node.nil? node.each_descendant(:send).select do |func_node| func_node.receiver.nil? && (func_name.nil? || func_name == func_node.method_name) end end # Given a method_name and arguments, yields to a block with # matching method passed as a parameter to the block. def find_method_with_args(node, method_name, *args) methods = find_every_method_call_by_name(node, method_name) methods.each do |method| next unless parameters_passed?(method, args) return true unless block_given? yield method end end # Matches a method with a receiver. Yields to a block with matching method node. # # ### Examples # # Match `Formula.factory(name)`. # # ```ruby # find_instance_method_call(node, "Formula", :factory) # ``` # # Match `build.head?`. # # ```ruby # find_instance_method_call(node, :build, :head?) # ``` def find_instance_method_call(node, instance, method_name) methods = find_every_method_call_by_name(node, method_name) methods.each do |method| next if method.receiver.nil? next if method.receiver.const_name != instance && !(method.receiver.send_type? && method.receiver.method_name == instance) @offensive_node = method return true unless block_given? yield method end end # Matches receiver part of method. Yields to a block with parent node of receiver. # # ### Example # # Match `ARGV.<whatever>()`. # # ```ruby # find_instance_call(node, "ARGV") # ``` def find_instance_call(node, name) node.each_descendant(:send) do |method_node| next if method_node.receiver.nil? next if method_node.receiver.const_name != name && !(method_node.receiver.send_type? && method_node.receiver.method_name == name) @offensive_node = method_node.receiver return true unless block_given? yield method_node end end # Find CONSTANTs in the source. # If block given, yield matching nodes. def find_const(node, const_name) return if node.nil? node.each_descendant(:const) do |const_node| next if const_node.const_name != const_name @offensive_node = const_node yield const_node if block_given? return true end nil end # To compare node with appropriate Ruby variable. def node_equals?(node, var) node == Parser::CurrentRuby.parse(var.inspect) end # Returns a block named block_name inside node. def find_block(node, block_name) return if node.nil? node.each_child_node(:block) do |block_node| next if block_node.method_name != block_name @offensive_node = block_node return block_node end # If not found then, parent node becomes the offensive node @offensive_node = node.parent nil end # Returns an array of block nodes named block_name inside node. def find_blocks(node, block_name) return if node.nil? node.each_child_node(:block).select { |block_node| block_name == block_node.method_name } end # Returns an array of block nodes of any depth below node in AST. # If a block is given then yields matching block node to the block! def find_all_blocks(node, block_name) return if node.nil? blocks = node.each_descendant(:block).select { |block_node| block_name == block_node.method_name } return blocks unless block_given? blocks.each do |block_node| offending_node(block_node) yield block_node end end # Returns a method definition node with method_name. # Returns first method def if method_name is nil. def find_method_def(node, method_name = nil) return if node.nil? node.each_child_node(:def) do |def_node| def_method_name = method_name(def_node) next if method_name != def_method_name && method_name.present? @offensive_node = def_node return def_node end return if node.parent.nil? # If not found then, parent node becomes the offensive node @offensive_node = node.parent nil end # Check if a block method is called inside a block. def block_method_called_in_block?(node, method_name) node.body.each_child_node do |call_node| next if !call_node.block_type? && !call_node.send_type? next if call_node.method_name != method_name @offensive_node = call_node return true end false end # Check if method_name is called among the direct children nodes in the given node. # Check if the node itself is the method. def method_called?(node, method_name) if node.send_type? && node.method_name == method_name offending_node(node) return true end node.each_child_node(:send) do |call_node| next if call_node.method_name != method_name offending_node(call_node) return true end false end # Check if method_name is called among every descendant node of given node. def method_called_ever?(node, method_name) node.each_descendant(:send) do |call_node| next if call_node.method_name != method_name @offensive_node = call_node return true end false end # Checks for precedence; returns the first pair of precedence-violating nodes. def check_precedence(first_nodes, next_nodes) next_nodes.each do |each_next_node| first_nodes.each do |each_first_node| return [each_first_node, each_next_node] if component_precedes?(each_first_node, each_next_node) end end nil end # If first node does not precede next_node, sets appropriate instance variables for reporting. def component_precedes?(first_node, next_node) return false if line_number(first_node) < line_number(next_node) @offensive_node = first_node true end # Check if negation is present in the given node. def expression_negated?(node) return false unless node.parent&.send_type? return false unless node.parent.method_name.equal?(:!) offending_node(node.parent) end # Returns the array of arguments of the method_node. def parameters(method_node) method_node.arguments if method_node.send_type? || method_node.block_type? end # Returns true if the given parameters are present in method call # and sets the method call as the offending node. # Params can be string, symbol, array, hash, matching regex. def parameters_passed?(method_node, params) method_params = parameters(method_node) @offensive_node = method_node params.all? do |given_param| method_params.any? do |method_param| if given_param.instance_of?(Regexp) regex_match_group(method_param, given_param) else node_equals?(method_param, given_param) end end end end # Returns the ending position of the node in source code. def end_column(node) node.source_range.end_pos end # Returns the class node's name, or nil if not a class node. def class_name(node) @offensive_node = node node.const_name end # Returns the method name for a def node. def method_name(node) node.children[0] if node.def_type? end # Returns the node size in the source code. def size(node) node.source_range.size end # Returns the block length of the block node. def block_size(block) block.loc.end.line - block.loc.begin.line end # Returns printable component name. def format_component(component_node) return component_node.method_name if component_node.send_type? || component_node.block_type? method_name(component_node) if component_node.def_type? end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/rubocops/shared/on_system_conditionals_helper.rb
Library/Homebrew/rubocops/shared/on_system_conditionals_helper.rb
# typed: strict # frozen_string_literal: true require "macos_version" require "rubocops/shared/helper_functions" module RuboCop module Cop # This module performs common checks on `on_{system}` blocks in both formulae and casks. module OnSystemConditionalsHelper extend NodePattern::Macros include HelperFunctions ARCH_OPTIONS = [:arm, :intel].freeze BASE_OS_OPTIONS = [:macos, :linux].freeze MACOS_VERSION_OPTIONS = T.let(MacOSVersion::SYMBOLS.keys.freeze, T::Array[Symbol]) ON_SYSTEM_OPTIONS = T.let( [*ARCH_OPTIONS, *BASE_OS_OPTIONS, *MACOS_VERSION_OPTIONS, :system].freeze, T::Array[Symbol], ) MACOS_MODULE_NAMES = ["MacOS", "OS::Mac"].freeze MACOS_VERSION_CONDITIONALS = T.let( { "==" => nil, "<=" => :or_older, ">=" => :or_newer, }.freeze, T::Hash[String, T.nilable(Symbol)], ) sig { params(body_node: RuboCop::AST::Node, parent_name: Symbol).void } def audit_on_system_blocks(body_node, parent_name) parent_string = if body_node.def_type? "def #{parent_name}" else "#{parent_name} do" end ON_SYSTEM_OPTIONS.each do |on_system_option| on_system_method = :"on_#{on_system_option}" if_statement_string = if ARCH_OPTIONS.include?(on_system_option) "if Hardware::CPU.#{on_system_option}?" elsif BASE_OS_OPTIONS.include?(on_system_option) "if OS.#{(on_system_option == :macos) ? "mac" : "linux"}?" elsif on_system_option == :system "if OS.linux? || MacOS.version" else "if MacOS.version" end find_every_method_call_by_name(body_node, on_system_method).each do |on_system_node| if_conditional = "" if MACOS_VERSION_OPTIONS.include? on_system_option on_macos_version_method_call(on_system_node, on_method: on_system_method) do |on_method_parameters| if on_method_parameters.empty? if_conditional = " == :#{on_system_option}" else if_condition_operator = MACOS_VERSION_CONDITIONALS.key(on_method_parameters.first) if_conditional = " #{if_condition_operator} :#{on_system_option}" end end elsif on_system_option == :system on_system_method_call(on_system_node) do |macos_symbol| base_os, condition = macos_symbol.to_s.split(/_(?=or_)/).map(&:to_sym) if_condition_operator = MACOS_VERSION_CONDITIONALS.key(condition) if_conditional = " #{if_condition_operator} :#{base_os}" end end offending_node(on_system_node) problem "Instead of using `#{on_system_node.source}` in `#{parent_string}`, " \ "use `#{if_statement_string}#{if_conditional}`." do |corrector| block_node = offending_node.parent next if block_node.type != :block # TODO: could fix corrector to handle this but punting for now. next if block_node.single_line? source_range = offending_node.source_range.join(offending_node.parent.loc.begin) corrector.replace(source_range, "#{if_statement_string}#{if_conditional}") end end end end sig { params( body_node: RuboCop::AST::Node, allowed_methods: T::Array[Symbol], allowed_blocks: T::Array[Symbol] ).void } def audit_arch_conditionals(body_node, allowed_methods: [], allowed_blocks: []) ARCH_OPTIONS.each do |arch_option| else_method = (arch_option == :arm) ? :on_intel : :on_arm if_arch_node_search(body_node, arch: :"#{arch_option}?") do |if_node, else_node| next if node_is_allowed?(if_node, allowed_methods:, allowed_blocks:) if_statement_problem(if_node, "if Hardware::CPU.#{arch_option}?", "on_#{arch_option}", else_method:, else_node:) end end [:arch, :arm?, :intel?].each do |method| hardware_cpu_search(body_node, method:) do |method_node| # These should already be caught by `if_arch_node_search` next if method_node.parent.source.start_with? "if #{method_node.source}" next if node_is_allowed?(method_node, allowed_methods:, allowed_blocks:) offending_node(method_node) problem "Instead of `#{method_node.source}`, use `on_arm` and `on_intel` blocks." end end end sig { params( body_node: RuboCop::AST::Node, allowed_methods: T::Array[Symbol], allowed_blocks: T::Array[Symbol] ).void } def audit_base_os_conditionals(body_node, allowed_methods: [], allowed_blocks: []) BASE_OS_OPTIONS.each do |base_os_option| os_method, else_method = if base_os_option == :macos [:mac?, :on_linux] else [:linux?, :on_macos] end if_base_os_node_search(body_node, base_os: os_method) do |if_node, else_node| next if node_is_allowed?(if_node, allowed_methods:, allowed_blocks:) if_statement_problem(if_node, "if OS.#{os_method}", "on_#{base_os_option}", else_method:, else_node:) end end end sig { params( body_node: RuboCop::AST::Node, allowed_methods: T::Array[Symbol], allowed_blocks: T::Array[Symbol], recommend_on_system: T::Boolean, ).void } def audit_macos_version_conditionals(body_node, allowed_methods: [], allowed_blocks: [], recommend_on_system: true) MACOS_VERSION_OPTIONS.each do |macos_version_option| if_macos_version_node_search(body_node, os_version: macos_version_option) do |if_node, operator, else_node| next if node_is_allowed?(if_node, allowed_methods:, allowed_blocks:) else_node = T.let(else_node, T.nilable(RuboCop::AST::Node)) autocorrect = else_node.blank? && MACOS_VERSION_CONDITIONALS.key?(operator.to_s) on_system_method_string = if recommend_on_system && operator == :< "on_system" elsif recommend_on_system && operator == :<= "on_system :linux, macos: :#{macos_version_option}_or_older" elsif operator != :== && MACOS_VERSION_CONDITIONALS.key?(operator.to_s) "on_#{macos_version_option} :#{MACOS_VERSION_CONDITIONALS[operator.to_s]}" else "on_#{macos_version_option}" end if_statement_problem(if_node, "if MacOS.version #{operator} :#{macos_version_option}", on_system_method_string, autocorrect:) end macos_version_comparison_search(body_node, os_version: macos_version_option) do |method_node| # These should already be caught by `if_macos_version_node_search` next if method_node.parent.source.start_with? "if #{method_node.source}" next if node_is_allowed?(method_node, allowed_methods:, allowed_blocks:) offending_node(method_node) problem "Instead of `#{method_node.source}`, use `on_{macos_version}` blocks." end end end sig { params( body_node: RuboCop::AST::Node, allowed_methods: T::Array[Symbol], allowed_blocks: T::Array[Symbol], ).void } def audit_macos_references(body_node, allowed_methods: [], allowed_blocks: []) MACOS_MODULE_NAMES.each do |macos_module_name| find_const(body_node, macos_module_name) do |node| next if node_is_allowed?(node, allowed_methods:, allowed_blocks:) offending_node(node) problem "Don't use `#{macos_module_name}` where it could be called on Linux." end end end private sig { params( if_node: RuboCop::AST::IfNode, if_statement_string: String, on_system_method_string: String, else_method: T.nilable(Symbol), else_node: T.nilable(RuboCop::AST::Node), autocorrect: T::Boolean, ).void } def if_statement_problem(if_node, if_statement_string, on_system_method_string, else_method: nil, else_node: nil, autocorrect: true) offending_node(if_node) problem "Instead of `#{if_statement_string}`, use `#{on_system_method_string} do`." do |corrector| next unless autocorrect # TODO: could fix corrector to handle this but punting for now. next if if_node.unless? if else_method.present? && else_node.present? corrector.replace(if_node.source_range, "#{on_system_method_string} do\n#{if_node.body.source}\nend\n" \ "#{else_method} do\n#{else_node.source}\nend") else corrector.replace(if_node.source_range, "#{on_system_method_string} do\n#{if_node.body.source}\nend") end end end sig { params( node: RuboCop::AST::Node, allowed_methods: T::Array[Symbol], allowed_blocks: T::Array[Symbol] ).returns(T::Boolean) } def node_is_allowed?(node, allowed_methods: [], allowed_blocks: []) # TODO: check to see if it's legal valid = T.let(false, T::Boolean) node.each_ancestor do |ancestor| valid_method_names = case ancestor.type when :def allowed_methods when :block allowed_blocks else next end next unless valid_method_names.include?(ancestor.method_name) valid = true break end return true if valid false end def_node_matcher :on_macos_version_method_call, <<~PATTERN (send nil? %on_method (sym ${:or_newer :or_older})?) PATTERN def_node_matcher :on_system_method_call, <<~PATTERN (send nil? :on_system (sym :linux) (hash (pair (sym :macos) (sym $_)))) PATTERN def_node_search :hardware_cpu_search, <<~PATTERN (send (const (const nil? :Hardware) :CPU) %method) PATTERN def_node_search :macos_version_comparison_search, <<~PATTERN (send (send (const nil? :MacOS) :version) {:== :<= :< :>= :> :!=} (sym %os_version)) PATTERN def_node_search :if_arch_node_search, <<~PATTERN $(if (send (const (const nil? :Hardware) :CPU) %arch) _ $_) PATTERN def_node_search :if_base_os_node_search, <<~PATTERN $(if (send (const nil? :OS) %base_os) _ $_) PATTERN def_node_search :if_macos_version_node_search, <<~PATTERN $(if (send (send (const nil? :MacOS) :version) ${:== :<= :< :>= :> :!=} (sym %os_version)) _ $_) PATTERN end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/manpages/converter/roff.rb
Library/Homebrew/manpages/converter/roff.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "kramdown/converter/man" module Homebrew module Manpages module Converter # Converts our Kramdown-like input to roff. class Roff < ::Kramdown::Converter::Man # Override that adds Homebrew metadata for the top level header # and doesn't escape the text inside subheaders. def convert_header(element, options) if element.options[:level] == 1 element.attr["data-date"] = Date.today.strftime("%B %Y") element.attr["data-extra"] = "Homebrew" return super end result = +"" inner(element, options.merge(result:)) result.gsub!(" [", ' \fR[') # make args not bold options[:result] << if element.options[:level] == 2 macro("SH", quote(result)) else macro("SS", quote(result)) end end def convert_variable(element, options) options[:result] << "\\fI#{escape(element.value)}\\fP" end def convert_a(element, options) if element.attr["href"].chr == "#" # Hide internal links - just make them italicised convert_em(element, options) else super # Remove the space after links if the next character is not a space if options[:result].end_with?(".UE\n") && (next_element = options[:next]) && next_element.type == :text && next_element.value.chr.present? # i.e. not a space character options[:result].chomp! options[:result] << " " end end end end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/manpages/converter/kramdown.rb
Library/Homebrew/manpages/converter/kramdown.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "kramdown/converter/kramdown" module Homebrew module Manpages module Converter # Converts our Kramdown-like input to pure Kramdown. class Kramdown < ::Kramdown::Converter::Kramdown def initialize(root, options) super(root, options.merge(line_width: 80)) end def convert_variable(element, _options) "*`#{element.value}`*" end def convert_a(element, options) text = inner(element, options) if element.attr["href"] == text # Don't duplicate the URL if the link text is the same as the URL. "<#{text}>" else super 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/manpages/parser/ronn.rb
Library/Homebrew/manpages/parser/ronn.rb
# typed: true # rubocop:todo Sorbet/StrictSigil # frozen_string_literal: true require "kramdown/parser/kramdown" module Homebrew module Manpages module Parser # Kramdown parser with compatiblity for ronn variable syntax. class Ronn < ::Kramdown::Parser::Kramdown def initialize(*) super # Disable HTML parsing and replace it with variable parsing. # Also disable table parsing too because it depends on HTML parsing # and existing command descriptions may get misinterpreted as tables. # Typographic symbols is disabled as it detects `--` as en-dash. @block_parsers.delete(:block_html) @block_parsers.delete(:table) @span_parsers.delete(:span_html) @span_parsers.delete(:typographic_syms) @span_parsers << :variable end # HTML-like tags denote variables instead, except <br>. VARIABLE_REGEX = /<([\w\-|]+)>/ def parse_variable start_line_number = @src.current_line_number @src.scan(VARIABLE_REGEX) variable = @src[1] if variable == "br" @src.skip(/\n/) @tree.children << Element.new(:br, nil, nil, location: start_line_number) else @tree.children << Element.new(:variable, variable, nil, location: start_line_number) end end define_parser(:variable, VARIABLE_REGEX, "<") 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/os/linux.rb
Library/Homebrew/os/linux.rb
# typed: strict # frozen_string_literal: true require "utils" module OS # Helper module for querying system information on Linux. module Linux raise "Loaded OS::Linux on generic OS!" if ENV["HOMEBREW_TEST_GENERIC_OS"] # This check is the only acceptable or necessary one in this file. # rubocop:disable Homebrew/MoveToExtendOS raise "Loaded OS::Linux on macOS!" if OS.mac? # rubocop:enable Homebrew/MoveToExtendOS @languages = T.let([], T::Array[String]) # Get the OS version. # # @api internal sig { returns(String) } def self.os_version if which("lsb_release") lsb_info = Utils.popen_read("lsb_release", "-a") description = lsb_info[/^Description:\s*(.*)$/, 1].force_encoding("UTF-8") codename = lsb_info[/^Codename:\s*(.*)$/, 1] if codename.blank? || (codename == "n/a") description else "#{description} (#{codename})" end elsif ::OS_VERSION.present? ::OS_VERSION else "Unknown" end end sig { returns(T::Boolean) } def self.wsl? /-microsoft/i.match?(OS.kernel_version.to_s) end sig { returns(Version) } def self.wsl_version return Version::NULL unless wsl? kernel = OS.kernel_version.to_s if Version.new(T.must(kernel[/^([0-9.]*)-.*/, 1])) > Version.new("5.15") Version.new("2 (Microsoft Store)") elsif kernel.include?("-microsoft") Version.new("2") elsif kernel.include?("-Microsoft") Version.new("1") else Version::NULL end end sig { returns(T::Array[String]) } def self.languages return @languages if @languages.present? locale_variables = ENV.keys.grep(/^(?:LC_\S+|LANG|LANGUAGE)\Z/).sort ctl_ret = Utils.popen_read("localectl", "list-locales") if ctl_ret.present? list = ctl_ret.scan(/[^ \n"(),]+/) elsif locale_variables.present? keys = locale_variables.select { |var| ENV.fetch(var) } list = keys.map { |key| ENV.fetch(key) } else list = ["en_US.utf8"] end @languages = list.map { |item| item.split(".").first.tr("_", "-") } end sig { returns(T.nilable(String)) } def self.language languages.first end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/os/mac.rb
Library/Homebrew/os/mac.rb
# typed: strict # frozen_string_literal: true require "macos_version" require "os/mac/xcode" require "os/mac/sdk" module OS # Helper module for querying system information on macOS. module Mac extend Utils::Output::Mixin raise "Loaded OS::Mac on generic OS!" if ENV["HOMEBREW_TEST_GENERIC_OS"] # This check is the only acceptable or necessary one in this file. # rubocop:disable Homebrew/MoveToExtendOS raise "Loaded OS::Mac on Linux!" if OS.linux? # rubocop:enable Homebrew/MoveToExtendOS # Provide MacOS alias for backwards compatibility and nicer APIs. ::MacOS = OS::Mac VERSION = T.let(ENV.fetch("HOMEBREW_MACOS_VERSION").chomp.freeze, String) private_constant :VERSION # This can be compared to numerics, strings, or symbols # using the standard Ruby Comparable methods. # # @api internal sig { returns(MacOSVersion) } def self.version @version ||= T.let(full_version.strip_patch, T.nilable(MacOSVersion)) end # This can be compared to numerics, strings, or symbols # using the standard Ruby Comparable methods. # # @api internal sig { returns(MacOSVersion) } def self.full_version @full_version ||= T.let(nil, T.nilable(MacOSVersion)) # HOMEBREW_FAKE_MACOS is set system-wide in the macOS 11-arm64-cross image # for building a macOS 11 Portable Ruby on macOS 12 # odisabled: remove support for Big Sur September (or later) 2027 @full_version ||= if (fake_macos = ENV.fetch("HOMEBREW_FAKE_MACOS", nil)) MacOSVersion.new(fake_macos) else MacOSVersion.new(VERSION) end end sig { params(version: String).void } def self.full_version=(version) @full_version = MacOSVersion.new(version.chomp) @version = nil end sig { returns(::Version) } def self.latest_sdk_version # TODO: bump version when new Xcode macOS SDK is released # NOTE: We only track the major version of the SDK. ::Version.new("26") end sig { returns(String) } def self.preferred_perl_version if version >= :sonoma "5.34" elsif version >= :big_sur "5.30" else "5.18" end end sig { returns(T::Array[String]) } def self.languages @languages ||= T.let(nil, T.nilable(T::Array[String])) return @languages if @languages os_langs = Utils.popen_read("defaults", "read", "-g", "AppleLanguages") if os_langs.blank? # User settings don't exist so check the system-wide one. os_langs = Utils.popen_read("defaults", "read", "/Library/Preferences/.GlobalPreferences", "AppleLanguages") end os_langs = T.cast(os_langs.scan(/[^ \n"(),]+/), T::Array[String]) @languages = os_langs end sig { returns(T.nilable(String)) } def self.language languages.first end sig { returns(String) } def self.active_developer_dir @active_developer_dir ||= T.let( Utils.popen_read("/usr/bin/xcode-select", "-print-path").strip, T.nilable(String), ) end sig { returns(T::Boolean) } def self.sdk_root_needed? odeprecated "OS::Mac.sdk_root_needed?" true end sig { returns(T.any(CLTSDKLocator, XcodeSDKLocator)) } def self.sdk_locator if CLT.installed? CLT.sdk_locator else Xcode.sdk_locator end end # If a specific SDK is requested: # # 1. The requested SDK is returned, if it's installed. # 2. If the requested SDK is not installed, the newest SDK (if any SDKs # are available) is returned. # 3. If no SDKs are available, nil is returned. # # If no specific SDK is requested, the SDK matching the OS version is returned, # if available. Otherwise, the latest SDK is returned. sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(SDK)) } def self.sdk(version = nil) sdk_locator.sdk_if_applicable(version) end # Returns the path to the SDK needed based on the formula's requirements. # # @api public sig { params( formula: Formula, version: T.nilable(MacOSVersion), check_only_runtime_requirements: T::Boolean, ).returns(T.nilable(SDK)) } def self.sdk_for_formula(formula, version = nil, check_only_runtime_requirements: false) # If the formula requires Xcode, don't return the CLT SDK # If check_only_runtime_requirements is true, don't necessarily return the # Xcode SDK if the XcodeRequirement is only a build or test requirement. return Xcode.sdk if formula.requirements.any? do |req| next false unless req.is_a? XcodeRequirement next false if check_only_runtime_requirements && req.build? && !req.test? true end sdk(version) end # Returns the path to an SDK or nil, following the rules set by {sdk}. # # @api public sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(::Pathname)) } def self.sdk_path(version = nil) s = sdk(version) s&.path end # Prefer CLT SDK when both Xcode and the CLT are installed. # Expected results: # 1. On Xcode-only systems, return the Xcode SDK. # 2. On CLT-only systems, return the CLT SDK. # # @api public sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(::Pathname)) } def self.sdk_path_if_needed(version = nil) sdk_path(version) end # See these issues for some history: # # - {https://github.com/Homebrew/legacy-homebrew/issues/13} # - {https://github.com/Homebrew/legacy-homebrew/issues/41} # - {https://github.com/Homebrew/legacy-homebrew/issues/48} sig { returns(T::Array[Pathname]) } def self.macports_or_fink paths = [] # First look in the path because MacPorts is relocatable and Fink # may become relocatable in the future. %w[port fink].each do |ponk| path = which(ponk) paths << path unless path.nil? end # Look in the standard locations, because even if port or fink are # not in the path they can still break builds if the build scripts # have these paths baked in. %w[/sw/bin/fink /opt/local/bin/port].each do |ponk| path = ::Pathname.new(ponk) paths << path if path.exist? end # Finally, some users make their MacPorts or Fink directories # read-only in order to try out Homebrew, but this doesn't work as # some build scripts error out when trying to read from these now # unreadable paths. %w[/sw /opt/local].map { |p| ::Pathname.new(p) }.each do |path| paths << path if path.exist? && !path.readable? end paths.uniq end sig { params(ids: String).returns(T.nilable(::Pathname)) } def self.app_with_bundle_id(*ids) require "bundle_version" paths = mdfind(*ids).filter_map do |bundle_path| ::Pathname.new(bundle_path) if bundle_path.exclude?("/Backups.backupdb/") end return paths.first unless paths.all? { |bp| (bp/"Contents/Info.plist").exist? } # Prefer newest one, if we can find it. paths.max_by { |bundle_path| Homebrew::BundleVersion.from_info_plist(bundle_path/"Contents/Info.plist") } end sig { params(ids: String).returns(T::Array[String]) } def self.mdfind(*ids) @mdfind ||= T.let(nil, T.nilable(T::Hash[T::Array[String], T::Array[String]])) (@mdfind ||= {}).fetch(ids) do @mdfind[ids] = Utils.popen_read("/usr/bin/mdfind", mdfind_query(*ids)).split("\n") end end sig { params(id: String).returns(String) } def self.pkgutil_info(id) @pkginfo ||= T.let(nil, T.nilable(T::Hash[String, String])) (@pkginfo ||= {}).fetch(id) do |key| @pkginfo[key] = Utils.popen_read("/usr/sbin/pkgutil", "--pkg-info", key).strip end end sig { params(ids: String).returns(String) } def self.mdfind_query(*ids) ids.map! { |id| "kMDItemCFBundleIdentifier == #{id}" }.join(" || ") end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/os/mac/sdk.rb
Library/Homebrew/os/mac/sdk.rb
# typed: strict # frozen_string_literal: true require "system_command" module OS module Mac # Class representing a macOS SDK. class SDK # 11.x SDKs are explicitly excluded - we want the MacOSX11.sdk symlink instead. VERSIONED_SDK_REGEX = /MacOSX(10\.\d+|\d+)\.sdk$/ sig { returns(MacOSVersion) } attr_reader :version sig { returns(::Pathname) } attr_reader :path sig { returns(Symbol) } attr_reader :source sig { params(version: MacOSVersion, path: T.any(String, ::Pathname), source: Symbol).void } def initialize(version, path, source) @version = version @path = T.let(Pathname(path), ::Pathname) @source = source end end # Base class for SDK locators. class BaseSDKLocator extend T::Helpers include SystemCommand::Mixin abstract! class NoSDKError < StandardError; end sig { void } def initialize @all_sdks = T.let(nil, T.nilable(T::Array[SDK])) @sdk_prefix = T.let(nil, T.nilable(String)) end sig { params(version: MacOSVersion).returns(SDK) } def sdk_for(version) sdk = all_sdks.find { |s| s.version == version } raise NoSDKError if sdk.nil? sdk end sig { returns(T::Array[SDK]) } def all_sdks return @all_sdks if @all_sdks @all_sdks = [] # Bail out if there is no SDK prefix at all return @all_sdks unless File.directory? sdk_prefix found_versions = Set.new Dir["#{sdk_prefix}/MacOSX*.sdk"].each do |sdk_path| next unless sdk_path.match?(SDK::VERSIONED_SDK_REGEX) version = read_sdk_version(::Pathname.new(sdk_path)) next if version.nil? @all_sdks << SDK.new(version, sdk_path, source) found_versions << version end # Use unversioned SDK only if we don't have one matching that version. sdk_path = ::Pathname.new("#{sdk_prefix}/MacOSX.sdk") if (version = read_sdk_version(sdk_path)) && found_versions.exclude?(version) @all_sdks << SDK.new(version, sdk_path, source) end @all_sdks end sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(SDK)) } def sdk_if_applicable(version = nil) sdk = begin if version.blank? sdk_for OS::Mac.version else sdk_for version end rescue NoSDKError latest_sdk end return if sdk.blank? # On OSs lower than 11, whenever the major versions don't match, # only return an SDK older than the OS version if it was specifically requested return if version.blank? && sdk.version < OS::Mac.version sdk end sig { abstract.returns(Symbol) } def source; end private sig { abstract.returns(String) } def sdk_prefix; end sig { returns(T.nilable(SDK)) } def latest_sdk all_sdks.max_by(&:version) end sig { params(sdk_path: ::Pathname).returns(T.nilable(MacOSVersion)) } def read_sdk_version(sdk_path) sdk_settings = sdk_path/"SDKSettings.json" sdk_settings_string = sdk_settings.read if sdk_settings.exist? return if sdk_settings_string.blank? sdk_settings_json = JSON.parse(sdk_settings_string) return if sdk_settings_json.blank? version_string = sdk_settings_json.fetch("Version", nil) return if version_string.blank? begin MacOSVersion.new(version_string).strip_patch rescue MacOSVersion::Error nil end end end private_constant :BaseSDKLocator # Helper class for locating the Xcode SDK. class XcodeSDKLocator < BaseSDKLocator sig { override.returns(Symbol) } def source :xcode end private sig { override.returns(String) } def sdk_prefix @sdk_prefix ||= begin # Xcode.prefix is pretty smart, so let's look inside to find the sdk sdk_prefix = "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs" # Finally query Xcode itself (this is slow, so check it last) if !File.directory?(sdk_prefix) && (xcrun = ::DevelopmentTools.locate("xcrun")) sdk_platform_path = Utils.popen_read(xcrun, "--show-sdk-platform-path").chomp sdk_prefix = File.join(sdk_platform_path, "Developer", "SDKs") end sdk_prefix end end end # Helper class for locating the macOS Command Line Tools SDK. class CLTSDKLocator < BaseSDKLocator sig { override.returns(Symbol) } def source :clt end private # As of Xcode 10, the Unix-style headers are installed via a # separate package, so we can't rely on their being present. sig { override.returns(String) } def sdk_prefix @sdk_prefix ||= "#{CLT::PKG_PATH}/SDKs" 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/os/mac/xcode.rb
Library/Homebrew/os/mac/xcode.rb
# typed: strict # frozen_string_literal: true module OS module Mac # Helper module for querying Xcode information. module Xcode DEFAULT_BUNDLE_PATH = T.let(Pathname("/Applications/Xcode.app").freeze, ::Pathname) BUNDLE_ID = "com.apple.dt.Xcode" OLD_BUNDLE_ID = "com.apple.Xcode" APPLE_DEVELOPER_DOWNLOAD_URL = "https://developer.apple.com/download/all/" # Bump these when a new version is available from the App Store and our # CI systems have been updated. # This may be a beta version for a beta macOS. sig { params(macos: MacOSVersion).returns(String) } def self.latest_version(macos: MacOS.version) macos = macos.strip_patch case macos when "26" then "26.0" when "15" then "16.4" when "14" then "16.2" when "13" then "15.2" when "12" then "14.2" when "11" then "13.2.1" when "10.15" then "12.4" else raise "macOS '#{macos}' is invalid" unless macos.prerelease? # Assume matching yearly Xcode release "#{macos}.0" end end # Bump these if things are badly broken (e.g. no SDK for this macOS) # without this. Generally this will be the first Xcode release on that # macOS version (which may initially be a beta if that version of macOS is # also in beta). sig { returns(String) } def self.minimum_version macos = MacOS.version case macos when "26" then "26.0" when "15" then "16.0" when "14" then "15.0" when "13" then "14.1" when "12" then "13.1" when "11" then "12.2" when "10.15" then "11.0" else "#{macos}.0" end end sig { returns(T::Boolean) } def self.below_minimum_version? return false unless installed? version < minimum_version end sig { returns(T::Boolean) } def self.latest_sdk_version? OS::Mac.full_version >= OS::Mac.latest_sdk_version end sig { returns(T::Boolean) } def self.needs_clt_installed? return false if latest_sdk_version? without_clt? end sig { returns(T::Boolean) } def self.outdated? return false unless installed? version < latest_version end sig { returns(T::Boolean) } def self.without_clt? !MacOS::CLT.installed? end # Returns a Pathname object corresponding to Xcode.app's Developer # directory or nil if Xcode.app is not installed. sig { returns(T.nilable(::Pathname)) } def self.prefix @prefix ||= T.let(begin dir = MacOS.active_developer_dir if dir.empty? || dir == CLT::PKG_PATH || !File.directory?(dir) path = bundle_path path/"Contents/Developer" if path else # Use cleanpath to avoid pathological trailing slash ::Pathname.new(dir).cleanpath end end, T.nilable(::Pathname)) end sig { returns(::Pathname) } def self.toolchain_path Pathname("#{prefix}/Toolchains/XcodeDefault.xctoolchain") end sig { returns(T.nilable(::Pathname)) } def self.bundle_path # Use the default location if it exists. return DEFAULT_BUNDLE_PATH if DEFAULT_BUNDLE_PATH.exist? # Ask Spotlight where Xcode is. If the user didn't install the # helper tools and installed Xcode in a non-conventional place, this # is our only option. See: https://superuser.com/questions/390757 MacOS.app_with_bundle_id(BUNDLE_ID, OLD_BUNDLE_ID) end sig { returns(T::Boolean) } def self.installed? !prefix.nil? end sig { returns(XcodeSDKLocator) } def self.sdk_locator @sdk_locator ||= T.let(XcodeSDKLocator.new, T.nilable(OS::Mac::XcodeSDKLocator)) end sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(SDK)) } def self.sdk(version = nil) sdk_locator.sdk_if_applicable(version) end sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(::Pathname)) } def self.sdk_path(version = nil) sdk(version)&.path end sig { returns(String) } def self.installation_instructions if OS::Mac.version.prerelease? <<~EOS Xcode can be installed from: #{Formatter.url(APPLE_DEVELOPER_DOWNLOAD_URL)} EOS else <<~EOS Xcode can be installed from the App Store. EOS end end sig { returns(String) } def self.update_instructions if OS::Mac.version.prerelease? <<~EOS Xcode can be updated from: #{Formatter.url(APPLE_DEVELOPER_DOWNLOAD_URL)} EOS else <<~EOS Xcode can be updated from the App Store. EOS end end # Get the Xcode version. # # @api internal sig { returns(::Version) } def self.version # may return a version string # that is guessed based on the compiler, so do not # use it in order to check if Xcode is installed. if @version ||= T.let(detect_version, T.nilable(String)) ::Version.new @version else ::Version::NULL end end sig { returns(T.nilable(String)) } def self.detect_version # This is a separate function as you can't cache the value out of a block # if return is used in the middle, which we do many times in here. return if !MacOS::Xcode.installed? && !MacOS::CLT.installed? if MacOS::Xcode.installed? # Fast path that will probably almost always work unless `xcode-select -p` is misconfigured version_plist = T.must(prefix).parent/"version.plist" if version_plist.file? data = Plist.parse_xml(version_plist, marshal: false) version = data["CFBundleShortVersionString"] if data return version if version end %W[ #{prefix}/usr/bin/xcodebuild #{which("xcodebuild")} ].uniq.each do |xcodebuild_path| next unless File.executable? xcodebuild_path xcodebuild_output = Utils.popen_read(xcodebuild_path, "-version") next unless $CHILD_STATUS.success? xcode_version = xcodebuild_output[/Xcode (\d+(\.\d+)*)/, 1] return xcode_version if xcode_version end end detect_version_from_clang_version end sig { params(version: ::Version).returns(String) } def self.detect_version_from_clang_version(version = ::DevelopmentTools.clang_version) return "dunno" if version.null? # This logic provides a fake Xcode version based on the # installed CLT version. This is useful as they are packaged # simultaneously so workarounds need to apply to both based on their # comparable version. case version when "11.0.0" then "11.3.1" when "11.0.3" then "11.7" when "12.0.0" then "12.4" when "12.0.5" then "12.5.1" when "13.0.0" then "13.2.1" when "13.1.6" then "13.4.1" when "14.0.0" then "14.2" when "14.0.3" then "14.3.1" when "15.0.0" then "15.4" when "16.0.0" then "16.2" else "26.0" end end sig { returns(T::Boolean) } def self.default_prefix? prefix.to_s == "/Applications/Xcode.app/Contents/Developer" end end # Helper module for querying macOS Command Line Tools information. module CLT extend Utils::Output::Mixin EXECUTABLE_PKG_ID = "com.apple.pkg.CLTools_Executables" PKG_PATH = "/Library/Developer/CommandLineTools" # Returns true even if outdated tools are installed. sig { returns(T::Boolean) } def self.installed? !version.null? end sig { returns(T::Boolean) } def self.separate_header_package? odeprecated "MacOS::CLT.separate_header_package?" true end sig { returns(CLTSDKLocator) } def self.sdk_locator @sdk_locator ||= T.let(CLTSDKLocator.new, T.nilable(OS::Mac::CLTSDKLocator)) end sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(SDK)) } def self.sdk(version = nil) sdk_locator.sdk_if_applicable(version) end sig { params(version: T.nilable(MacOSVersion)).returns(T.nilable(::Pathname)) } def self.sdk_path(version = nil) sdk(version)&.path end sig { returns(String) } def self.installation_instructions if OS::Mac.version.prerelease? <<~EOS Install the Command Line Tools for Xcode #{minimum_version.split(".").first} from: #{Formatter.url(MacOS::Xcode::APPLE_DEVELOPER_DOWNLOAD_URL)} EOS else <<~EOS Install the Command Line Tools: xcode-select --install EOS end end sig { params(reason: String).returns(String) } def self.reinstall_instructions(reason: "resolve your issues") <<~EOS If that doesn't #{reason}, run: sudo rm -rf /Library/Developer/CommandLineTools sudo xcode-select --install Alternatively, manually download them from: #{Formatter.url(MacOS::Xcode::APPLE_DEVELOPER_DOWNLOAD_URL)}. You should download the Command Line Tools for Xcode #{MacOS::Xcode.latest_version}. EOS end sig { returns(String) } def self.update_instructions return installation_instructions if OS::Mac.version.prerelease? software_update_location = if MacOS.version >= "13" "System Settings" else "System Preferences" end <<~EOS Update them from Software Update in #{software_update_location}. #{reinstall_instructions(reason: "show you any updates")} EOS end sig { returns(String) } def self.installation_then_reinstall_instructions <<~EOS #{installation_instructions} #{reinstall_instructions} EOS end # Bump these when the new version is distributed through Software Update # and our CI systems have been updated. sig { returns(String) } def self.latest_clang_version case MacOS.version when "26" then "1700.3.19.1" when "15" then "1700.0.13.5" when "14" then "1600.0.26.6" when "13" then "1500.1.0.2.5" when "12" then "1400.0.29.202" when "11" then "1300.0.29.30" else "1200.0.32.29" end end # Bump these if things are badly broken (e.g. no SDK for this macOS) # without this. Generally this will be the first stable CLT release on # that macOS version. sig { returns(String) } def self.minimum_version macos = MacOS.version case macos when "15" then "16.0.0" when "14" then "15.0.0" when "13" then "14.0.0" when "12" then "13.0.0" when "11" then "12.5.0" when "10.15" then "11.0.0" else "#{macos}.0.0" end end sig { returns(T::Boolean) } def self.below_minimum_version? return false unless installed? version < minimum_version end sig { returns(T::Boolean) } def self.outdated? clang_version = detect_clang_version return false unless clang_version ::Version.new(clang_version) < latest_clang_version end sig { returns(T.nilable(String)) } def self.detect_clang_version version_output = Utils.popen_read("#{PKG_PATH}/usr/bin/clang", "--version") version_output[/clang-(\d+(\.\d+)+)/, 1] end sig { returns(T.nilable(String)) } def self.detect_version_from_clang_version clang_version = detect_clang_version return if clang_version.nil? MacOS::Xcode.detect_version_from_clang_version(Version.new(clang_version)) end # Version string (a pretty long one) of the CLT package. # Note that the different ways of installing the CLTs lead to different # version numbers. # # @api internal sig { returns(::Version) } def self.version if @version ||= T.let(detect_version, T.nilable(String)) ::Version.new @version else ::Version::NULL end end sig { returns(T.nilable(String)) } def self.detect_version version = T.let(nil, T.nilable(String)) if File.exist?("#{PKG_PATH}/usr/bin/clang") version = MacOS.pkgutil_info(EXECUTABLE_PKG_ID)[/version: (.+)$/, 1] return version if version end detect_version_from_clang_version 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/os/mac/mach.rb
Library/Homebrew/os/mac/mach.rb
# typed: strict # frozen_string_literal: true require "macho" # {Pathname} extension for dealing with Mach-O files. module MachOShim extend Forwardable extend T::Helpers requires_ancestor { Pathname } delegate [:dylib_id] => :macho sig { params(args: T.untyped).void } def initialize(*args) @macho = T.let(nil, T.nilable(T.any(MachO::MachOFile, MachO::FatFile))) @mach_data = T.let(nil, T.nilable(T::Array[T::Hash[Symbol, Symbol]])) super end sig { returns(T.any(MachO::MachOFile, MachO::FatFile)) } def macho @macho ||= MachO.open(to_s) end private :macho sig { returns(T::Array[T::Hash[Symbol, Symbol]]) } def mach_data @mach_data ||= begin machos = [] mach_data = [] case (macho = self.macho) when MachO::FatFile machos = macho.machos else machos << macho end machos.each do |m| arch = case m.cputype when :x86_64, :i386, :ppc64, :arm64, :arm then m.cputype when :ppc then :ppc7400 else :dunno end type = case m.filetype when :dylib, :bundle then m.filetype when :execute then :executable else :dunno end mach_data << { arch:, type: } end mach_data rescue MachO::NotAMachOError # Silently ignore errors that indicate the file is not a Mach-O binary ... [] rescue # ... but complain about other (parse) errors for further investigation. onoe "Failed to read Mach-O binary: #{self}" raise if Homebrew::EnvConfig.developer? [] end end private :mach_data # TODO: See if the `#write!` call can be delayed until # we know we're not making any changes to the rpaths. sig { params(rpath: String, strict: T::Boolean).void } def delete_rpath(rpath, strict: true) candidates = rpaths(resolve_variable_references: false).select do |r| resolve_variable_name(r) == resolve_variable_name(rpath) end # Delete the last instance to avoid changing the order in which rpaths are searched. rpath_to_delete = candidates.last macho.delete_rpath(rpath_to_delete, { last: true, strict: }) macho.write! end sig { params(old: String, new: String, uniq: T::Boolean, last: T::Boolean, strict: T::Boolean).void } def change_rpath(old, new, uniq: false, last: false, strict: true) macho.change_rpath(old, new, { uniq:, last:, strict: }) macho.write! end sig { params(id: String, strict: T::Boolean).void } def change_dylib_id(id, strict: true) macho.change_dylib_id(id, { strict: }) macho.write! end sig { params(old: String, new: String, strict: T::Boolean).void } def change_install_name(old, new, strict: true) macho.change_install_name(old, new, { strict: }) macho.write! end sig { params(except: Symbol, resolve_variable_references: T::Boolean).returns(T::Array[String]) } def dynamically_linked_libraries(except: :none, resolve_variable_references: true) lcs = macho.dylib_load_commands lcs.reject! { |lc| lc.flag?(except) } if except != :none names = lcs.map { |lc| lc.name.to_s }.uniq names.map! { resolve_variable_name(it) } if resolve_variable_references names end sig { params(resolve_variable_references: T::Boolean).returns(T::Array[String]) } def rpaths(resolve_variable_references: true) names = macho.rpaths # Don't recursively resolve rpaths to avoid infinite loops. names.map! { |name| resolve_variable_name(name, resolve_rpaths: false) } if resolve_variable_references names end sig { params(name: String, resolve_rpaths: T::Boolean).returns(String) } def resolve_variable_name(name, resolve_rpaths: true) if name.start_with? "@loader_path" Pathname(name.sub("@loader_path", dirname.to_s)).cleanpath.to_s elsif name.start_with?("@executable_path") && binary_executable? Pathname(name.sub("@executable_path", dirname.to_s)).cleanpath.to_s elsif resolve_rpaths && name.start_with?("@rpath") && (target = resolve_rpath(name)).present? target else name end end sig { params(name: String).returns(T.nilable(String)) } def resolve_rpath(name) target = T.let(nil, T.nilable(String)) return unless rpaths(resolve_variable_references: true).find do |rpath| File.exist?(target = File.join(rpath, name.delete_prefix("@rpath"))) end target end sig { returns(T::Array[Symbol]) } def archs mach_data.map { |m| m.fetch :arch } end sig { returns(Symbol) } def arch case archs.length when 0 then :dunno when 1 then archs.fetch(0) else :universal end end sig { returns(T::Boolean) } def universal? arch == :universal end sig { returns(T::Boolean) } def i386? arch == :i386 end sig { returns(T::Boolean) } def x86_64? arch == :x86_64 end sig { returns(T::Boolean) } def ppc7400? arch == :ppc7400 end sig { returns(T::Boolean) } def ppc64? arch == :ppc64 end sig { returns(T::Boolean) } def dylib? mach_data.any? { |m| m.fetch(:type) == :dylib } end sig { returns(T::Boolean) } def mach_o_executable? mach_data.any? { |m| m.fetch(:type) == :executable } end alias binary_executable? mach_o_executable? sig { returns(T::Boolean) } def mach_o_bundle? mach_data.any? { |m| m.fetch(:type) == :bundle } end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/os/linux/ld.rb
Library/Homebrew/os/linux/ld.rb
# typed: strict # frozen_string_literal: true module OS module Linux # Helper functions for querying `ld` information. module Ld # This is a list of known paths to the host dynamic linker on Linux if # the host glibc is new enough. Brew will fail to create a symlink for # ld.so if the host linker cannot be found in this list. DYNAMIC_LINKERS = %w[ /lib64/ld-linux-x86-64.so.2 /lib64/ld64.so.2 /lib/ld-linux.so.3 /lib/ld-linux.so.2 /lib/ld-linux-aarch64.so.1 /lib/ld-linux-armhf.so.3 /system/bin/linker64 /system/bin/linker ].freeze # The path to the system's dynamic linker or `nil` if not found sig { returns(T.nilable(::Pathname)) } def self.system_ld_so @system_ld_so ||= T.let(nil, T.nilable(::Pathname)) @system_ld_so ||= begin linker = DYNAMIC_LINKERS.find { |s| File.executable? s } Pathname(linker) if linker end end sig { params(brewed: T::Boolean).returns(String) } def self.ld_so_diagnostics(brewed: true) @ld_so_diagnostics ||= T.let({}, T.nilable(T::Hash[Pathname, T.nilable(String)])) ld_so_target = if brewed ld_so = HOMEBREW_PREFIX/"lib/ld.so" return "" unless ld_so.exist? ld_so.readlink else ld_so = system_ld_so return "" unless ld_so&.exist? ld_so end @ld_so_diagnostics[ld_so_target] ||= begin ld_so_output = Utils.popen_read(ld_so, "--list-diagnostics") ld_so_output if $CHILD_STATUS.success? end @ld_so_diagnostics[ld_so_target].to_s end sig { params(brewed: T::Boolean).returns(String) } def self.sysconfdir(brewed: true) fallback_sysconfdir = "/etc" match = ld_so_diagnostics(brewed:).match(/path.sysconfdir="(.+)"/) return fallback_sysconfdir unless match match.captures.compact.first || fallback_sysconfdir end sig { params(brewed: T::Boolean).returns(T::Array[String]) } def self.system_dirs(brewed: true) dirs = [] ld_so_diagnostics(brewed:).split("\n").each do |line| match = line.match(/path.system_dirs\[0x.*\]="(.*)"/) next unless match dirs << match.captures.compact.first end dirs end sig { params(conf_path: T.any(::Pathname, String), brewed: T::Boolean).returns(T::Array[String]) } def self.library_paths(conf_path = "ld.so.conf", brewed: true) conf_file = Pathname(sysconfdir(brewed:))/conf_path return [] unless conf_file.exist? return [] unless conf_file.file? return [] unless conf_file.readable? @library_paths_cache ||= T.let({}, T.nilable(T::Hash[String, T::Array[String]])) cache_key = conf_file.to_s if (cached_library_path_contents = @library_paths_cache[cache_key]) return cached_library_path_contents end paths = Set.new directory = conf_file.realpath.dirname conf_file.open("r") do |file| file.each_line do |line| # Remove comments and leading/trailing whitespace line.strip! line.sub!(/\s*#.*$/, "") if line.start_with?(/\s*include\s+/) wildcard = Pathname(line.sub(/^\s*include\s+/, "")).expand_path(directory) Dir.glob(wildcard.to_s).each do |include_file| paths += library_paths(include_file) end elsif line.empty? next else paths << line end end end @library_paths_cache[cache_key] = paths.to_a end end end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/os/linux/libstdcxx.rb
Library/Homebrew/os/linux/libstdcxx.rb
# typed: strict # frozen_string_literal: true require "os/linux/ld" module OS module Linux # Helper functions for querying `libstdc++` information. module Libstdcxx SOVERSION = 6 SONAME = T.let("libstdc++.so.#{SOVERSION}".freeze, String) sig { returns(T::Boolean) } def self.below_ci_version? system_version < LINUX_LIBSTDCXX_CI_VERSION end sig { returns(Version) } def self.system_version @system_version ||= T.let(nil, T.nilable(Version)) @system_version ||= if (path = system_path) Version.new("#{SOVERSION}#{path.realpath.basename.to_s.delete_prefix!(SONAME)}") else Version::NULL end end sig { returns(T.nilable(::Pathname)) } def self.system_path @system_path ||= T.let(nil, T.nilable(::Pathname)) @system_path ||= find_library(OS::Linux::Ld.library_paths(brewed: false)) @system_path ||= find_library(OS::Linux::Ld.system_dirs(brewed: false)) end sig { params(paths: T::Array[String]).returns(T.nilable(::Pathname)) } private_class_method def self.find_library(paths) paths.each do |path| next if path.start_with?(HOMEBREW_PREFIX) candidate = Pathname(path)/SONAME elf_candidate = ELFPathname.wrap(candidate) return candidate if candidate.exist? && elf_candidate.elf? end 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/os/linux/glibc.rb
Library/Homebrew/os/linux/glibc.rb
# typed: strict # frozen_string_literal: true module OS module Linux # Helper functions for querying `glibc` information. module Glibc module_function sig { returns(Version) } def system_version @system_version ||= T.let(nil, T.nilable(Version)) @system_version ||= begin version = Utils.popen_read("/usr/bin/ldd", "--version")[/ (\d+\.\d+)/, 1] if version Version.new version else Version::NULL end end end sig { returns(Version) } def version @version ||= T.let(nil, T.nilable(Version)) @version ||= begin version = Utils.popen_read(HOMEBREW_PREFIX/"opt/glibc/bin/ldd", "--version")[/ (\d+\.\d+)/, 1] if version Version.new version else system_version end end end sig { returns(Version) } def minimum_version Version.new(ENV.fetch("HOMEBREW_LINUX_MINIMUM_GLIBC_VERSION")) end sig { returns(T::Boolean) } def below_minimum_version? system_version < minimum_version end sig { returns(T::Boolean) } def below_ci_version? system_version < LINUX_GLIBC_CI_VERSION 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/os/linux/kernel.rb
Library/Homebrew/os/linux/kernel.rb
# typed: strict # frozen_string_literal: true module OS module Linux # Helper functions for querying Linux kernel information. module Kernel module_function sig { returns(Version) } def minimum_version Version.new "3.2" end sig { returns(T::Boolean) } def below_minimum_version? OS.kernel_version < minimum_version 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/os/linux/elf.rb
Library/Homebrew/os/linux/elf.rb
# typed: strict # frozen_string_literal: true require "os/linux/ld" # {Pathname} extension for dealing with ELF files. # @see https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header module ELFShim extend T::Helpers MAGIC_NUMBER_OFFSET = 0 private_constant :MAGIC_NUMBER_OFFSET MAGIC_NUMBER_ASCII = "\x7fELF" private_constant :MAGIC_NUMBER_ASCII OS_ABI_OFFSET = 0x07 private_constant :OS_ABI_OFFSET OS_ABI_SYSTEM_V = 0 private_constant :OS_ABI_SYSTEM_V OS_ABI_LINUX = 3 private_constant :OS_ABI_LINUX TYPE_OFFSET = 0x10 private_constant :TYPE_OFFSET TYPE_EXECUTABLE = 2 private_constant :TYPE_EXECUTABLE TYPE_SHARED = 3 private_constant :TYPE_SHARED ARCHITECTURE_OFFSET = 0x12 private_constant :ARCHITECTURE_OFFSET ARCHITECTURE_I386 = 0x3 private_constant :ARCHITECTURE_I386 ARCHITECTURE_POWERPC = 0x14 private_constant :ARCHITECTURE_POWERPC ARCHITECTURE_POWERPC64 = 0x15 private_constant :ARCHITECTURE_POWERPC64 ARCHITECTURE_ARM = 0x28 private_constant :ARCHITECTURE_ARM ARCHITECTURE_X86_64 = 0x3E private_constant :ARCHITECTURE_X86_64 ARCHITECTURE_AARCH64 = 0xB7 private_constant :ARCHITECTURE_AARCH64 requires_ancestor { Pathname } sig { params(path: T.anything).void } def initialize(path) @elf = T.let(nil, T.nilable(T::Boolean)) @arch = T.let(nil, T.nilable(Symbol)) @elf_type = T.let(nil, T.nilable(Symbol)) @rpath = T.let(nil, T.nilable(String)) @interpreter = T.let(nil, T.nilable(String)) @dynamic_elf = T.let(nil, T.nilable(T::Boolean)) @metadata = T.let(nil, T.nilable(Metadata)) super end sig { params(offset: Integer).returns(Integer) } def read_uint8(offset) read(1, offset).unpack1("C") end sig { params(offset: Integer).returns(Integer) } def read_uint16(offset) read(2, offset).unpack1("v") end sig { returns(T::Boolean) } def elf? return @elf unless @elf.nil? return @elf = false if read(MAGIC_NUMBER_ASCII.size, MAGIC_NUMBER_OFFSET) != MAGIC_NUMBER_ASCII # Check that this ELF file is for Linux or System V. # OS_ABI is often set to 0 (System V), regardless of the target platform. @elf = [OS_ABI_LINUX, OS_ABI_SYSTEM_V].include? read_uint8(OS_ABI_OFFSET) end sig { returns(Symbol) } def arch return :dunno unless elf? @arch ||= case read_uint16(ARCHITECTURE_OFFSET) when ARCHITECTURE_I386 then :i386 when ARCHITECTURE_X86_64 then :x86_64 when ARCHITECTURE_POWERPC then :ppc32 when ARCHITECTURE_POWERPC64 then :ppc64 when ARCHITECTURE_ARM then :arm when ARCHITECTURE_AARCH64 then :arm64 else :dunno end end sig { params(wanted_arch: Symbol).returns(T::Boolean) } def arch_compatible?(wanted_arch) return true unless elf? # Treat ppc64le and ppc64 the same wanted_arch = :ppc64 if wanted_arch == :ppc64le wanted_arch == arch end sig { returns(Symbol) } def elf_type return :dunno unless elf? @elf_type ||= case read_uint16(TYPE_OFFSET) when TYPE_EXECUTABLE then :executable when TYPE_SHARED then :dylib else :dunno end end sig { returns(T::Boolean) } def dylib? elf_type == :dylib end sig { returns(T::Boolean) } def binary_executable? elf_type == :executable end # The runtime search path, such as: # "/lib:/usr/lib:/usr/local/lib" sig { returns(T.nilable(String)) } def rpath metadata.rpath end # An array of runtime search path entries, such as: # ["/lib", "/usr/lib", "/usr/local/lib"] sig { returns(T::Array[String]) } def rpaths Array(rpath&.split(":")) end sig { returns(T.nilable(String)) } def interpreter metadata.interpreter end sig { params(interpreter: T.nilable(String), rpath: T.nilable(String)).void } def patch!(interpreter: nil, rpath: nil) return if interpreter.blank? && rpath.blank? save_using_patchelf_rb interpreter, rpath end sig { returns(T::Boolean) } def dynamic_elf? metadata.dynamic_elf? end sig { returns(T::Array[String]) } def section_names metadata.section_names end # Helper class for reading metadata from an ELF file. class Metadata sig { returns(ELFShim) } attr_reader :path sig { returns(T.nilable(String)) } attr_reader :dylib_id sig { returns(T::Boolean) } def dynamic_elf? @dynamic_elf end sig { returns(T.nilable(String)) } attr_reader :interpreter sig { returns(T.nilable(String)) } attr_reader :rpath sig { returns(T::Array[String]) } attr_reader :section_names sig { params(path: ELFShim).void } def initialize(path) require "patchelf" patcher = path.patchelf_patcher @path = path @dylibs = T.let(nil, T.nilable(T::Array[String])) @dylib_id = T.let(nil, T.nilable(String)) @needed = T.let([], T::Array[String]) dynamic_segment = patcher.elf.segment_by_type(:dynamic) @dynamic_elf = T.let(dynamic_segment.present?, T::Boolean) @dylib_id, @needed = if @dynamic_elf [patcher.soname, patcher.needed] else [nil, []] end @interpreter = T.let(patcher.interpreter, T.nilable(String)) @rpath = T.let(patcher.runpath || patcher.rpath, T.nilable(String)) @section_names = T.let(patcher.elf.sections.map(&:name).compact_blank, T::Array[String]) @dt_flags_1 = T.let(dynamic_segment&.tag_by_type(:flags_1)&.value, T.nilable(Integer)) end sig { returns(T::Array[String]) } def dylibs @dylibs ||= @needed.map { |lib| find_full_lib_path(lib).to_s } end private sig { params(basename: String).returns(::Pathname) } def find_full_lib_path(basename) basename = ::Pathname.new(basename) local_paths = rpath&.split(":") # Search for dependencies in the runpath/rpath first local_paths&.each do |local_path| local_path = OS::Linux::Elf.expand_elf_dst(local_path, "ORIGIN", path.parent) candidate = ::Pathname.new(local_path)/basename elf_candidate = ELFPathname.wrap(candidate) return candidate if candidate.exist? && elf_candidate.elf? end # Check if DF_1_NODEFLIB is set nodeflib_flag = if @dt_flags_1.nil? false else @dt_flags_1 & ELFTools::Constants::DF::DF_1_NODEFLIB != 0 end linker_library_paths = OS::Linux::Ld.library_paths linker_system_dirs = OS::Linux::Ld.system_dirs # If DF_1_NODEFLIB is set, exclude any library paths that are subdirectories # of the system dirs if nodeflib_flag linker_library_paths = linker_library_paths.reject do |lib_path| linker_system_dirs.any? { |system_dir| Utils::Path.child_of? system_dir, lib_path } end end # If not found, search recursively in the paths listed in ld.so.conf (skipping # paths that are subdirectories of the system dirs if DF_1_NODEFLIB is set) linker_library_paths.each do |linker_library_path| candidate = Pathname(linker_library_path)/basename elf_candidate = ELFPathname.wrap(candidate) return candidate if candidate.exist? && elf_candidate.elf? end # If not found, search in the system dirs, unless DF_1_NODEFLIB is set unless nodeflib_flag linker_system_dirs.each do |linker_system_dir| candidate = Pathname(linker_system_dir)/basename elf_candidate = ELFPathname.wrap(candidate) return candidate if candidate.exist? && elf_candidate.elf? end end basename end end private_constant :Metadata sig { params(new_interpreter: T.nilable(String), new_rpath: T.nilable(String)).void } def save_using_patchelf_rb(new_interpreter, new_rpath) patcher = patchelf_patcher patcher.interpreter = new_interpreter if new_interpreter.present? patcher.rpath = new_rpath if new_rpath.present? patcher.save(patchelf_compatible: true) end # Don't cache the patcher; it keeps the ELF file open so long as it is alive. # Instead, for read-only access to the ELF file's metadata, fetch it and cache # it with {Metadata}. sig { returns(::PatchELF::Patcher) } def patchelf_patcher require "patchelf" ::PatchELF::Patcher.new to_s, on_error: :silent end sig { returns(Metadata) } def metadata @metadata ||= Metadata.new(self) end private :metadata sig { returns(T.nilable(String)) } def dylib_id metadata.dylib_id end sig { params(except: Symbol, resolve_variable_references: T::Boolean).returns(T::Array[String]) } def dynamically_linked_libraries(except: :none, resolve_variable_references: true) metadata.dylibs end end module OS module Linux # Helper functions for working with ELF objects. # # @api private module Elf sig { params(str: String, ref: String, repl: T.any(String, ::Pathname)).returns(String) } def self.expand_elf_dst(str, ref, repl) # ELF gABI rules for DSTs: # - Longest possible sequence using the rules (greedy). # - Must start with a $ (enforced by caller). # - Must follow $ with one underscore or ASCII [A-Za-z] (caller # follows these rules for REF) or '{' (start curly quoted name). # - Must follow first two characters with zero or more [A-Za-z0-9_] # (enforced by caller) or '}' (end curly quoted name). # (from https://github.com/bminor/glibc/blob/41903cb6f460d62ba6dd2f4883116e2a624ee6f8/elf/dl-load.c#L182-L228) # In addition to capturing a token, also attempt to capture opening/closing braces and check that they are not # mismatched before expanding. str.gsub(/\$({?)([a-zA-Z_][a-zA-Z0-9_]*)(}?)/) do |orig_str| has_opening_brace = ::Regexp.last_match(1).present? matched_text = ::Regexp.last_match(2) has_closing_brace = ::Regexp.last_match(3).present? if (matched_text == ref) && (has_opening_brace == has_closing_brace) repl else orig_str 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/formula-analytics/pycall-setup.rb
Library/Homebrew/formula-analytics/pycall-setup.rb
# typed: strict # frozen_string_literal: true require "pycall/import" # This was a rewrite from `include(Module.new(...))`, # to appease Sorbet, so let's keep the existing behaviour # and silence RuboCop. # rubocop:disable Style/MixinUsage include PyCall::Import # rubocop:enable Style/MixinUsage pyfrom "influxdb_client_3", import: :InfluxDBClient3
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/optparse.rb
Library/Homebrew/extend/optparse.rb
# typed: strict # frozen_string_literal: true require "optparse" OptionParser.accept Pathname do |path| Pathname(path).expand_path if path end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/blank.rb
Library/Homebrew/extend/blank.rb
# typed: strict # frozen_string_literal: true class Object # An object is blank if it's false, empty, or a whitespace string. # # For example, `nil`, `''`, `' '`, `[]`, `{}` and `false` are all blank. # # ### Example # # ```ruby # !address || address.empty? # ``` # # can be simplified to # # ```ruby # address.blank? # ``` sig { returns(T::Boolean) } def blank? respond_to?(:empty?) ? !!T.unsafe(self).empty? : false end # An object is present if it's not blank. sig { returns(T::Boolean) } def present? = !blank? # Returns the receiver if it's present, otherwise returns `nil`. # # `object.presence` is equivalent to `object.present? ? object : nil`. # # ### Example # # ```ruby # state = params[:state] if params[:state].present? # country = params[:country] if params[:country].present? # region = state || country || 'US' # ``` # # can be simplified to # # ```ruby # region = params[:state].presence || params[:country].presence || 'US' # ``` sig { returns(T.nilable(T.self_type)) } def presence self if present? end end class NilClass # `nil` is blank: # # ```ruby # nil.blank? # => true # ``` sig { returns(TrueClass) } def blank? = true sig { returns(FalseClass) } def present? = false # :nodoc: end class FalseClass # `false` is blank: # # ```ruby # false.blank? # => true # ``` sig { returns(TrueClass) } def blank? = true sig { returns(FalseClass) } def present? = false # :nodoc: end class TrueClass # `true` is not blank: # # ```ruby # true.blank? # => false # ``` sig { returns(FalseClass) } def blank? = false sig { returns(TrueClass) } def present? = true # :nodoc: end class Array # An array is blank if it's empty: # # ```ruby # [].blank? # => true # [1,2,3].blank? # => false # ``` sig { returns(T::Boolean) } def blank? = empty? sig { returns(T::Boolean) } def present? = !empty? # :nodoc: end class Hash # A hash is blank if it's empty: # # # ```ruby # {}.blank? # => true # { key: 'value' }.blank? # => false # ``` sig { returns(T::Boolean) } def blank? = empty? sig { returns(T::Boolean) } def present? = !empty? # :nodoc: end class Symbol # A Symbol is blank if it's empty: # # ```ruby # :''.blank? # => true # :symbol.blank? # => false # ``` sig { returns(T::Boolean) } def blank? = empty? sig { returns(T::Boolean) } def present? = !empty? # :nodoc: end class String BLANK_RE = /\A[[:space:]]*\z/ # This is a cache that is intentionally mutable # rubocop:disable Style/MutableConstant ENCODED_BLANKS_ = T.let(Hash.new do |h, enc| h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING) end, T::Hash[Encoding, Regexp]) # rubocop:enable Style/MutableConstant # A string is blank if it's empty or contains whitespaces only: # # ```ruby # ''.blank? # => true # ' '.blank? # => true # "\t\n\r".blank? # => true # ' blah '.blank? # => false # ``` # # Unicode whitespace is supported: # # ```ruby # "\u00a0".blank? # => true # ``` sig { returns(T::Boolean) } def blank? # The regexp that matches blank strings is expensive. For the case of empty # strings we can speed up this method (~3.5x) with an empty? call. The # penalty for the rest of strings is marginal. empty? || begin BLANK_RE.match?(self) rescue Encoding::CompatibilityError T.must(ENCODED_BLANKS_[encoding]).match?(self) end end sig { returns(T::Boolean) } def present? = !blank? # :nodoc: end class Numeric # :nodoc: # No number is blank: # # ```ruby # 1.blank? # => false # 0.blank? # => false # ``` sig { returns(FalseClass) } def blank? = false sig { returns(TrueClass) } def present? = true end class Time # :nodoc: # No Time is blank: # # ```ruby # Time.now.blank? # => false # ``` sig { returns(FalseClass) } def blank? = false sig { returns(TrueClass) } def present? = true end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/array.rb
Library/Homebrew/extend/array.rb
# typed: strict # frozen_string_literal: true class Array # Equal to `self[1]`. # # ### Example # # ```ruby # %w( a b c d e ).second # => "b" # ``` def second = self[1] # Equal to `self[2]`. # # ### Example # # ```ruby # %w( a b c d e ).third # => "c" # ``` def third = self[2] # Equal to `self[3]`. # # ### Example # # ```ruby # %w( a b c d e ).fourth # => "d" # ``` def fourth = self[3] # Equal to `self[4]`. # # ### Example # # ```ruby # %w( a b c d e ).fifth # => "e" # ``` def fifth = self[4] # Converts the array to a comma-separated sentence where the last element is # joined by the connector word. # # ### Examples # # ```ruby # [].to_sentence # => "" # ['one'].to_sentence # => "one" # ['one', 'two'].to_sentence # => "one and two" # ['one', 'two', 'three'].to_sentence # => "one, two and three" # ['one', 'two'].to_sentence(two_words_connector: '-') # # => "one-two" # ``` # # ``` # ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ') # # => "one or two or at least three" # ``` # # @see https://github.com/rails/rails/blob/v7.0.4.2/activesupport/lib/active_support/core_ext/array/conversions.rb#L8-L84 # ActiveSupport Array#to_sentence monkey-patch # # # Copyright (c) David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense and/or sell copies of the Software and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # # @param [String] words_connector The sign or word used to join all but the last # element in arrays with three or more elements (default: `", "`). # @param [String] last_word_connector The sign or word used to join the last element # in arrays with three or more elements (default: `" and "`). # @param [String] two_words_connector The sign or word used to join the elements # in arrays with two elements (default: `" and "`). sig { params(words_connector: String, two_words_connector: String, last_word_connector: String).returns(String) } def to_sentence(words_connector: ", ", two_words_connector: " and ", last_word_connector: " and ") case length when 0 +"" when 1 # This is not typesafe, if the array contains a BasicObject +T.unsafe(self[0]).to_s when 2 "#{self[0]}#{two_words_connector}#{self[1]}" else "#{T.must(self[0...-1]).join(words_connector)}#{last_word_connector}#{self[-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/extend/kernel.rb
Library/Homebrew/extend/kernel.rb
# typed: strict # frozen_string_literal: true require "utils/output" module Kernel sig { params(env: T.nilable(String)).returns(T::Boolean) } def superenv?(env) return false if env == "std" !Superenv.bin.nil? end private :superenv? sig { params(formula: T.nilable(Formula)).void } def interactive_shell(formula = nil) unless formula.nil? ENV["HOMEBREW_DEBUG_PREFIX"] = formula.prefix.to_s ENV["HOMEBREW_DEBUG_INSTALL"] = formula.full_name end if Utils::Shell.preferred == :zsh && (home = Dir.home).start_with?(HOMEBREW_TEMP.resolved_path.to_s) FileUtils.mkdir_p home FileUtils.touch "#{home}/.zshrc" end term = ENV.fetch("HOMEBREW_TERM", ENV.fetch("TERM", nil)) with_env(TERM: term) do Process.wait fork { exec Utils::Shell.preferred_path(default: "/bin/bash") } end return if $CHILD_STATUS.success? raise "Aborted due to non-zero exit status (#{$CHILD_STATUS.exitstatus})" if $CHILD_STATUS.exited? raise $CHILD_STATUS.inspect end sig { type_parameters(:U).params(block: T.proc.returns(T.type_parameter(:U))).returns(T.type_parameter(:U)) } def with_homebrew_path(&block) with_env(PATH: PATH.new(ORIGINAL_PATHS).to_s, &block) end sig { type_parameters(:U) .params(locale: String, block: T.proc.returns(T.type_parameter(:U))) .returns(T.type_parameter(:U)) } def with_custom_locale(locale, &block) with_env(LC_ALL: locale, &block) end # Kernel.system but with exceptions. sig { params( cmd: T.nilable(T.any(Pathname, String, [String, String], T::Hash[String, T.nilable(String)])), argv0: T.nilable(T.any(Pathname, String, [String, String])), args: T.nilable(T.any(Pathname, String)), options: T.untyped, ).void } def safe_system(cmd, argv0 = nil, *args, **options) # TODO: migrate to utils.rb Homebrew.safe_system require "utils" return if Homebrew.system(cmd, argv0, *args, **options) raise ErrorDuringExecution.new([cmd, argv0, *args], status: $CHILD_STATUS) end # Run a system command without any output. # # @api internal sig { params( cmd: T.nilable(T.any(Pathname, String, [String, String], T::Hash[String, T.nilable(String)])), argv0: T.nilable(T.any(String, [String, String])), args: T.any(Pathname, String), ).returns(T::Boolean) } def quiet_system(cmd, argv0 = nil, *args) # TODO: migrate to utils.rb Homebrew.quiet_system require "utils" Homebrew._system(cmd, argv0, *args) do # Redirect output streams to `/dev/null` instead of closing as some programs # will fail to execute if they can't write to an open stream. $stdout.reopen(File::NULL) $stderr.reopen(File::NULL) end end # Find a command. # # @api public sig { params(cmd: String, path: PATH::Elements).returns(T.nilable(Pathname)) } def which(cmd, path = ENV.fetch("PATH")) PATH.new(path).each do |p| begin pcmd = File.expand_path(cmd, p) rescue ArgumentError # File.expand_path will raise an ArgumentError if the path is malformed. # See https://github.com/Homebrew/legacy-homebrew/issues/32789 next end return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd) end nil end sig { params(silent: T::Boolean).returns(String) } def which_editor(silent: false) editor = Homebrew::EnvConfig.editor return editor if editor # Find VS Code variants, Sublime Text, Textmate, BBEdit, or vim editor = %w[code codium cursor code-insiders subl mate bbedit vim].find do |candidate| candidate if which(candidate, ORIGINAL_PATHS) end editor ||= "vim" unless silent Utils::Output.opoo <<~EOS Using #{editor} because no editor was set in the environment. This may change in the future, so we recommend setting `$EDITOR` or `$HOMEBREW_EDITOR` to your preferred text editor. EOS end editor end sig { params(filenames: T.any(String, Pathname)).void } def exec_editor(*filenames) puts "Editing #{filenames.join "\n"}" with_homebrew_path { safe_system(*which_editor.shellsplit, *filenames) } end sig { params(args: T.any(String, Pathname)).void } def exec_browser(*args) browser = Homebrew::EnvConfig.browser browser ||= OS::PATH_OPEN if defined?(OS::PATH_OPEN) return unless browser ENV["DISPLAY"] = Homebrew::EnvConfig.display with_env(DBUS_SESSION_BUS_ADDRESS: ENV.fetch("HOMEBREW_DBUS_SESSION_BUS_ADDRESS", nil)) do safe_system(browser, *args) end end IGNORE_INTERRUPTS_MUTEX = T.let(Thread::Mutex.new.freeze, Thread::Mutex) sig { type_parameters(:U).params(_block: T.proc.returns(T.type_parameter(:U))).returns(T.type_parameter(:U)) } def ignore_interrupts(&_block) IGNORE_INTERRUPTS_MUTEX.synchronize do interrupted = T.let(false, T::Boolean) old_sigint_handler = trap(:INT) do interrupted = true $stderr.print "\n" $stderr.puts "One sec, cleaning up..." end begin yield ensure trap(:INT, old_sigint_handler) raise Interrupt if interrupted end end end sig { type_parameters(:U) .params(file: T.any(IO, Pathname, String), _block: T.proc.returns(T.type_parameter(:U))) .returns(T.type_parameter(:U)) } def redirect_stdout(file, &_block) out = $stdout.dup $stdout.reopen(file) yield ensure $stdout.reopen(out) out.close end # Ensure the given executable exists otherwise install the brewed version sig { params(name: String, formula_name: T.nilable(String), reason: String, latest: T::Boolean).returns(Pathname) } def ensure_executable!(name, formula_name = nil, reason: "", latest: false) formula_name ||= name executable = [ which(name), which(name, ORIGINAL_PATHS), # We prefer the opt_bin path to a formula's executable over the prefix # path where available, since the former is stable during upgrades. HOMEBREW_PREFIX/"opt/#{formula_name}/bin/#{name}", HOMEBREW_PREFIX/"bin/#{name}", ].compact.find(&:exist?) return executable if executable require "formula" Formulary.factory_stub(formula_name).ensure_installed!(reason:, latest:).opt_bin/name end sig { params( size_in_bytes: T.any(Integer, Float), precision: T.nilable(Integer), ).returns([T.any(Integer, Float), String]) } def disk_usage_readable_size_unit(size_in_bytes, precision: nil) size = size_in_bytes unit = "B" %w[KB MB GB].each do |next_unit| break if (precision ? size.abs.round(precision) : size.abs) < 1000 size /= 1000.0 unit = next_unit end [size, unit] end sig { params(size_in_bytes: T.any(Integer, Float)).returns(String) } def disk_usage_readable(size_in_bytes) size, unit = disk_usage_readable_size_unit(size_in_bytes) # avoid trailing zero after decimal point if ((size * 10).to_i % 10).zero? "#{size.to_i}#{unit}" else "#{format("%<size>.1f", size:)}#{unit}" end end sig { params(number: Integer).returns(String) } def number_readable(number) numstr = number.to_i.to_s (numstr.size - 3).step(1, -3) { |i| numstr.insert(i.to_i, ",") } numstr end # Truncates a text string to fit within a byte size constraint, # preserving character encoding validity. The returned string will # be not much longer than the specified max_bytes, though the exact # shortfall or overrun may vary. sig { params(str: String, max_bytes: Integer, options: T::Hash[Symbol, T.untyped]).returns(String) } def truncate_text_to_approximate_size(str, max_bytes, options = {}) front_weight = options.fetch(:front_weight, 0.5) raise "opts[:front_weight] must be between 0.0 and 1.0" if front_weight < 0.0 || front_weight > 1.0 return str if str.bytesize <= max_bytes glue = "\n[...snip...]\n" max_bytes_in = [max_bytes - glue.bytesize, 1].max bytes = str.dup.force_encoding("BINARY") glue_bytes = glue.encode("BINARY") n_front_bytes = (max_bytes_in * front_weight).floor n_back_bytes = max_bytes_in - n_front_bytes if n_front_bytes.zero? front = bytes[1..0] back = bytes[-max_bytes_in..] elsif n_back_bytes.zero? front = bytes[0..(max_bytes_in - 1)] back = bytes[1..0] else front = bytes[0..(n_front_bytes - 1)] back = bytes[-n_back_bytes..] end out = T.must(front) + glue_bytes + T.must(back) out.force_encoding("UTF-8") out.encode!("UTF-16", invalid: :replace) out.encode!("UTF-8") out end # Calls the given block with the passed environment variables # added to `ENV`, then restores `ENV` afterwards. # # NOTE: This method is **not** thread-safe – other threads # which happen to be scheduled during the block will also # see these environment variables. # # ### Example # # ```ruby # with_env(PATH: "/bin") do # system "echo $PATH" # end # ``` # # @api public sig { type_parameters(:U) .params( hash: T::Hash[Object, T.nilable(T.any(PATH, Pathname, String))], _block: T.proc.returns(T.type_parameter(:U)), ).returns(T.type_parameter(:U)) } def with_env(hash, &_block) old_values = {} begin hash.each do |key, value| key = key.to_s old_values[key] = ENV.delete(key) ENV[key] = value&.to_s end yield ensure ENV.update(old_values) end end sig { returns(T.proc.params(a: String, b: String).returns(Integer)) } def tap_and_name_comparison proc do |a, b| if a.include?("/") && b.exclude?("/") 1 elsif a.exclude?("/") && b.include?("/") -1 else a <=> b end end end sig { params(input: String, secrets: T::Array[String]).returns(String) } def redact_secrets(input, secrets) secrets.compact .reduce(input) { |str, secret| str.gsub secret, "******" } .freeze end end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/string.rb
Library/Homebrew/extend/string.rb
# typed: strict # frozen_string_literal: true class String # The inverse of <tt>String#include?</tt>. Returns true if the string # does not include the other string. # # "hello".exclude? "lo" # => false # "hello".exclude? "ol" # => true # "hello".exclude? ?h # => false sig { params(string: String).returns(T::Boolean) } def exclude?(string) = !include?(string) end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/ENV.rb
Library/Homebrew/extend/ENV.rb
# typed: strict # frozen_string_literal: true require "hardware" require "diagnostic" require "extend/ENV/shared" require "extend/ENV/std" require "extend/ENV/super" # <!-- vale off --> # @!parse # # `ENV` is not actually a class, but this makes YARD happy # # @see https://rubydoc.info/stdlib/core/ENV # # <code>ENV</code> core documentation # # @see Superenv # # @see Stdenv # class ENV; end # <!-- vale on --> module EnvActivation sig { params(env: T.nilable(String)).void } def activate_extensions!(env: nil) if superenv?(env) extend(Superenv) else extend(Stdenv) end end sig { type_parameters(:U).params( env: T.nilable(String), cc: T.nilable(String), build_bottle: T::Boolean, bottle_arch: T.nilable(String), debug_symbols: T.nilable(T::Boolean), _block: T.proc.returns(T.type_parameter(:U)), ).returns(T.type_parameter(:U)) } def with_build_environment(env: nil, cc: nil, build_bottle: false, bottle_arch: nil, debug_symbols: false, &_block) old_env = to_hash.dup tmp_env = to_hash.dup.extend(EnvActivation) T.cast(tmp_env, EnvActivation).activate_extensions!(env:) T.cast(tmp_env, T.any(Superenv, Stdenv)) .setup_build_environment(cc:, build_bottle:, bottle_arch:, debug_symbols:) replace(tmp_env) begin yield ensure replace(old_env) end end sig { params(key: T.any(String, Symbol)).returns(T::Boolean) } def sensitive?(key) key.match?(/(cookie|key|token|password|passphrase)/i) end sig { returns(T::Hash[String, String]) } def sensitive_environment select { |key, _| sensitive?(key) } end sig { void } def clear_sensitive_environment! each_key { |key| delete key if sensitive?(key) } end end ENV.extend(EnvActivation)
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/enumerable.rb
Library/Homebrew/extend/enumerable.rb
# typed: strict # frozen_string_literal: true module Enumerable # The negative of the {Enumerable#include?}. Returns `true` if the # collection does not include the object. sig { params(object: T.untyped).returns(T::Boolean) } def exclude?(object) = !include?(object) # Returns a new +Array+ without the blank items. # Uses Object#blank? for determining if an item is blank. # # ### Examples # # ``` # [1, "", nil, 2, " ", [], {}, false, true].compact_blank # # => [1, 2, true] # ``` # # ```ruby # Set.new([nil, "", 1, false]).compact_blank # # => [1] # ``` # # When called on a {Hash}, returns a new {Hash} without the blank values. # # ```ruby # { a: "", b: 1, c: nil, d: [], e: false, f: true }.compact_blank # # => { b: 1, f: true } # ``` sig { returns(T.self_type) } def compact_blank = T.unsafe(self).reject(&:blank?) end class Hash # {Hash#reject} has its own definition, so this needs one too. def compact_blank = reject { |_k, v| T.unsafe(v).blank? } end
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false
Homebrew/brew
https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/pathname.rb
Library/Homebrew/extend/pathname.rb
# typed: strict # frozen_string_literal: true require "system_command" require "extend/pathname/disk_usage_extension" require "extend/pathname/observer_pathname_extension" require "extend/pathname/write_mkpath_extension" require "utils/output" # Stubs needed to keep Sorbet happy. module MachOShim; end module ELFShim; end # @api private module BinaryPathname sig { params(path: T.any(Pathname, String, MachOShim, ELFShim)).returns(T.any(MachOShim, ELFShim)) } def self.wrap(path) = raise NotImplementedError end # Homebrew extends Ruby's `Pathname` to make our code more readable. # @see https://ruby-doc.org/stdlib-2.6.3/libdoc/pathname/rdoc/Pathname.html Ruby's Pathname API class Pathname include SystemCommand::Mixin include DiskUsageExtension include Utils::Output::Mixin sig { void } def self.activate_extensions! Pathname.prepend(WriteMkpathExtension) end # Moves a file from the original location to the {Pathname}'s. # # @api public sig { params(sources: T.any( Resource, Resource::Partial, String, Pathname, T::Array[T.any(String, Pathname)], T::Hash[T.any(String, Pathname), String] )).void } def install(*sources) sources.each do |src| case src when Resource src.stage(self) when Resource::Partial src.resource.stage { install(*src.files) } when Array if src.empty? opoo "Tried to install empty array to #{self}" break end src.each { |s| install_p(s, File.basename(s)) } when Hash if src.empty? opoo "Tried to install empty hash to #{self}" break end src.each { |s, new_basename| install_p(s, new_basename) } else install_p(src, File.basename(src)) end end end # Creates symlinks to sources in this folder. # # @api public sig { params( sources: T.any(String, Pathname, T::Array[T.any(String, Pathname)], T::Hash[T.any(String, Pathname), String]), ).void } def install_symlink(*sources) sources.each do |src| case src when Array src.each { |s| install_symlink_p(s, File.basename(s)) } when Hash src.each { |s, new_basename| install_symlink_p(s, new_basename) } else install_symlink_p(src, File.basename(src)) end end end # Only appends to a file that is already created. # # @api public sig { params(content: String, open_args: T.untyped).void } def append_lines(content, **open_args) raise "Cannot append file that doesn't exist: #{self}" unless exist? T.unsafe(self).open("a", **open_args) { |f| f.puts(content) } end # Write to a file atomically. # # NOTE: This always overwrites. # # @api public sig { params(content: String).void } def atomic_write(content) require "extend/file/atomic" old_stat = stat if exist? File.atomic_write(self) do |file| file.write(content) end return unless old_stat # Try to restore original file's permissions separately # atomic_write does it itself, but it actually erases # them if chown fails begin # Set correct permissions on new file chown(old_stat.uid, nil) chown(nil, old_stat.gid) rescue Errno::EPERM, Errno::EACCES # Changing file ownership failed, moving on. nil end begin # This operation will affect filesystem ACL's chmod(old_stat.mode) rescue Errno::EPERM, Errno::EACCES # Changing file permissions failed, moving on. nil end end sig { params(pattern: T.any(Pathname, String, Regexp), replacement: T.any(Pathname, String), _block: T.nilable(T.proc.params(src: Pathname, dst: Pathname).returns(Pathname))).void } def cp_path_sub(pattern, replacement, &_block) raise "#{self} does not exist" unless exist? pattern = pattern.to_s if pattern.is_a?(Pathname) replacement = replacement.to_s if replacement.is_a?(Pathname) dst = sub(pattern, replacement) raise "#{self} is the same file as #{dst}" if self == dst if directory? dst.mkpath else dst.dirname.mkpath dst = yield(self, dst) if block_given? FileUtils.cp(self, dst) end end # Extended to support common double extensions. # # @api public sig { returns(String) } def extname basename = File.basename(self) bottle_ext, = HOMEBREW_BOTTLES_EXTNAME_REGEX.match(basename).to_a return bottle_ext if bottle_ext archive_ext = basename[/(\.(tar|cpio|pax)\.(gz|bz2|lz|xz|zst|Z))\Z/, 1] return archive_ext if archive_ext # Don't treat version numbers as extname. return "" if basename.match?(/\b\d+\.\d+[^.]*\Z/) && !basename.end_with?(".7z") File.extname(basename) end # For filetypes we support, returns basename without extension. # # @api public sig { returns(String) } def stem File.basename(self, extname) end # I don't trust the children.length == 0 check particularly, not to mention # it is slow to enumerate the whole directory just to see if it is empty, # instead rely on good ol' libc and the filesystem sig { returns(T::Boolean) } def rmdir_if_possible rmdir true rescue Errno::ENOTEMPTY if (ds_store = join(".DS_Store")).exist? && children.length == 1 ds_store.unlink retry else false end rescue Errno::EACCES, Errno::ENOENT, Errno::EBUSY, Errno::EPERM false end sig { returns(Version) } def version require "version" Version.parse(basename) end sig { returns(T::Boolean) } def text_executable? /\A#!\s*\S+/.match?(open("r") { |f| f.read(1024) }) end sig { returns(String) } def sha256 require "digest/sha2" Digest::SHA256.file(self).hexdigest end sig { params(expected: T.nilable(Checksum)).void } def verify_checksum(expected) raise ChecksumMissingError if expected.blank? actual = Checksum.new(sha256.downcase) raise ChecksumMismatchError.new(self, expected, actual) if expected != actual end alias to_str to_s # Change to this directory, optionally executing the given block. # # @api public sig { type_parameters(:U).params( _block: T.proc.params(path: Pathname).returns(T.type_parameter(:U)), ).returns(T.type_parameter(:U)) } def cd(&_block) Dir.chdir(self) { yield self } end # Get all sub-directories of this directory. # # @api public sig { returns(T::Array[Pathname]) } def subdirs children.select(&:directory?) end sig { returns(Pathname) } def resolved_path symlink? ? dirname.join(readlink) : self end sig { returns(T::Boolean) } def resolved_path_exists? link = readlink rescue ArgumentError # The link target contains NUL bytes false else dirname.join(link).exist? end sig { params(src: Pathname).void } def make_relative_symlink(src) dirname.mkpath File.symlink(src.relative_path_from(dirname), self) end sig { params(_block: T.proc.void).void } def ensure_writable(&_block) saved_perms = nil unless writable? saved_perms = stat.mode FileUtils.chmod "u+rw", to_path end yield ensure chmod saved_perms if saved_perms end sig { void } def install_info quiet_system(which_install_info, "--quiet", to_s, "#{dirname}/dir") end sig { void } def uninstall_info quiet_system(which_install_info, "--delete", "--quiet", to_s, "#{dirname}/dir") end # Writes an exec script in this folder for each target pathname. sig { params(targets: T.any(T::Array[T.any(String, Pathname)], String, Pathname)).void } def write_exec_script(*targets) targets.flatten! if targets.empty? opoo "Tried to write exec scripts to #{self} for an empty list of targets" return end mkpath targets.each do |target| target = Pathname.new(target) # allow pathnames or strings join(target.basename).write <<~SH #!/bin/bash exec "#{target}" "$@" SH end end # Writes an exec script that sets environment variables. sig { params(target: T.any(Pathname, String), args_or_env: T.any(String, T::Array[String], T::Hash[String, String], T::Hash[Symbol, String]), env: T.any(T::Hash[String, String], T::Hash[Symbol, String])).void } def write_env_script(target, args_or_env, env = T.unsafe(nil)) args = if env.nil? env = args_or_env if args_or_env.is_a?(Hash) nil elsif args_or_env.is_a?(Array) args_or_env.join(" ") else T.cast(args_or_env, T.nilable(String)) end env_export = +"" env.each { |key, value| env_export << "#{key}=\"#{value}\" " } dirname.mkpath write <<~SH #!/bin/bash #{env_export}exec "#{target}" #{args} "$@" SH end # Writes a wrapper env script and moves all files to the dst. sig { params(dst: Pathname, env: T::Hash[String, String]).void } def env_script_all_files(dst, env) dst.mkpath Pathname.glob("#{self}/*") do |file| next if file.directory? new_file = dst.join(file.basename) raise Errno::EEXIST, new_file.to_s if new_file.exist? dst.install(file) file.write_env_script(new_file, env) end end # Writes an exec script that invokes a Java jar. sig { params( target_jar: T.any(String, Pathname), script_name: T.any(String, Pathname), java_opts: String, java_version: T.nilable(String), ).returns(Integer) } def write_jar_script(target_jar, script_name, java_opts = "", java_version: nil) mkpath (self/script_name).write <<~EOS #!/bin/bash export JAVA_HOME="#{Language::Java.overridable_java_home_env(java_version)[:JAVA_HOME]}" exec "${JAVA_HOME}/bin/java" #{java_opts} -jar "#{target_jar}" "$@" EOS end sig { params(from: T.any(String, Pathname)).void } def install_metafiles(from = Pathname.pwd) require "metafiles" Pathname(from).children.each do |p| next if p.directory? next if File.empty?(p) next unless Metafiles.copy?(p.basename.to_s) # Some software symlinks these files (see help2man.rb) filename = p.resolved_path # Some software links metafiles together, so by the time we iterate to one of them # we may have already moved it. libxml2's COPYING and Copyright are affected by this. next unless filename.exist? filename.chmod 0644 install(filename) end end sig { returns(T::Boolean) } def ds_store? basename.to_s == ".DS_Store" end sig { returns(T::Boolean) } def binary_executable? false end sig { returns(T::Boolean) } def mach_o_bundle? false end sig { returns(T::Boolean) } def dylib? false end sig { params(_wanted_arch: Symbol).returns(T::Boolean) } def arch_compatible?(_wanted_arch) true end sig { returns(T::Array[String]) } def rpaths [] end sig { returns(String) } def magic_number @magic_number ||= T.let(nil, T.nilable(String)) @magic_number ||= if directory? "" else # Length of the longest regex (currently Tar). max_magic_number_length = 262 binread(max_magic_number_length) || "" end end sig { returns(String) } def file_type @file_type ||= T.let(nil, T.nilable(String)) @file_type ||= system_command("file", args: ["-b", self], print_stderr: false) .stdout.chomp end sig { returns(T::Array[String]) } def zipinfo @zipinfo ||= T.let( system_command("zipinfo", args: ["-1", self], print_stderr: false) .stdout .encode(Encoding::UTF_8, invalid: :replace) .split("\n"), T.nilable(T::Array[String]), ) end private sig { params(src: T.any(String, Pathname), new_basename: T.any(String, Pathname), _block: T.nilable(T.proc.params(src: Pathname, dst: Pathname).returns(T.nilable(Pathname)))).void } def install_p(src, new_basename, &_block) src = Pathname(src) raise Errno::ENOENT, src.to_s if !src.symlink? && !src.exist? dst = join(new_basename) dst = yield(src, dst) if block_given? return unless dst mkpath # Use `FileUtils.mv` over `File.rename` to handle filesystem boundaries. If `src` # is a symlink and its target is moved first, `FileUtils.mv` will fail # (https://bugs.ruby-lang.org/issues/7707). # # In that case, use the system `mv` command. if src.symlink? raise unless Kernel.system "mv", src.to_s, dst.to_s else FileUtils.mv src, dst end end sig { params(src: T.any(String, Pathname), new_basename: T.any(String, Pathname)).void } def install_symlink_p(src, new_basename) mkpath dstdir = realpath src = Pathname(src).expand_path(dstdir) src = src.dirname.realpath/src.basename if src.dirname.exist? FileUtils.ln_sf(src.relative_path_from(dstdir), dstdir/new_basename) end sig { returns(T.nilable(String)) } def which_install_info @which_install_info ||= T.let(nil, T.nilable(String)) @which_install_info ||= if File.executable?("/usr/bin/install-info") "/usr/bin/install-info" elsif (texinfo_formula = Formulary.factory_stub("texinfo")).any_version_installed? (texinfo_formula.opt_bin/"install-info").to_s end end end require "extend/os/pathname"
ruby
BSD-2-Clause
fe0a384e3a04605192726c149570fbe33a8996b0
2026-01-04T15:37:27.366412Z
false