Class: Keg Private

Inherits:
Object show all
Extended by:
Cacheable, Forwardable, T::Generic, Utils::Output::Mixin
Includes:
OS::Linux::Keg, OS::Mac::Keg, Utils::Output::Mixin, Utils::Path
Defined in:
keg.rb,
keg_relocate.rb,
keg.rbi,
sorbet/rbi/dsl/keg.rbi

This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

Defined Under Namespace

Classes: AlreadyLinkedError, ConflictError, DirectoryNotWritableError, DynamicStringReferences, LinkError, Relocation

Constant Summary collapse

Cache =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

type_template { { fixed: T::Hash[Symbol, T.untyped] } }
LOCALEDIR_RX =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

Locale-specific directories have the form language[_territory][.codeset][@modifier]

%r{(?:locale|man)/(?:[a-z]{2}|C|POSIX)(?:_[A-Z]{2})?(?:\.[a-zA-Z\-0-9]+(?:@.+)?)?}
INFOFILE_RX =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%r{info/(?:[^.].*?\.info(?:\.gz)?|dir)$}
SHARE_PATHS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

These paths relative to the keg's share directory should always be real directories in the prefix, never symlinks.

%w[
  aclocal cps doc info java locale man
  man/man1 man/man2 man/man3 man/man4
  man/man5 man/man6 man/man7 man/man8
  man/cat1 man/cat2 man/cat3 man/cat4
  man/cat5 man/cat6 man/cat7 man/cat8
  applications gnome gnome/help icons
  mime mime/packages mime-info pixmaps
  postgresql sounds
].freeze
ELISP_EXTENSIONS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%w[.el .elc].freeze
PYC_EXTENSIONS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%w[.pyc .pyo].freeze
LIBTOOL_EXTENSIONS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%w[.la .lai].freeze
KEEPME_FILE =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

".keepme"
PREFIX_PLACEHOLDER =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"@@HOMEBREW_PREFIX@@"
CELLAR_PLACEHOLDER =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"@@HOMEBREW_CELLAR@@"
REPOSITORY_PLACEHOLDER =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"@@HOMEBREW_REPOSITORY@@"
LIBRARY_PLACEHOLDER =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"@@HOMEBREW_LIBRARY@@"
PERL_PLACEHOLDER =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"@@HOMEBREW_PERL@@"
JAVA_PLACEHOLDER =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"@@HOMEBREW_JAVA@@"
NULL_BYTE =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"\x00"
NULL_BYTE_STRING =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"\\x00"
JAVA_REGEX =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%r{#{HOMEBREW_PREFIX}/opt/openjdk(?:@\d+(?:\.\d+)*)?/libexec(?:/openjdk\.jdk/Contents/Home)?}

Constants included from OS::Mac::Keg

OS::Mac::Keg::FRAMEWORK_RX, OS::Mac::Keg::VARIABLE_REFERENCE_RX

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Cacheable

cache, clear_cache

Methods included from Utils::Output::Mixin

issue_reporting_message, odebug, odeprecated, odie, odisabled, ofail, oh1, oh1_title, ohai, ohai_title, onoe, opoo, opoo_once, opoo_outside_github_actions, opoo_without_github_actions_annotation, pretty_cannot_install, pretty_deprecated, pretty_disabled, pretty_duration, pretty_install_status, pretty_installed, pretty_uninstalled, pretty_unmarked, pretty_upgradable, pretty_warning

Methods included from OS::Mac::Keg

#change_dylib_id, #change_install_name, #change_rpath, #delete_rpath, #dylib_id_for, #each_linkage_for, #find_dylib, #find_dylib_suffix_from, #fixed_name, #formula_preserve_rpath?, #loader_name_for, #mach_o_files, #relocated_name_for

Methods included from SystemCommand::Mixin

#command_sandbox, #system_command, #system_command!

Methods included from Utils::Path

formula_installed_prefixes, formula_opt_bin_env, formula_opt_bin_path, install_info, loadable_package_path?, uninstall_info

Methods included from Utils::Path::Helpers

#child_of?, #cp_path_sub, #ensure_child_of!, #ensure_writable, #resolved_path, #resolved_path_exists?, #rmdir_if_possible, #text_executable?

Methods included from Utils::Path::FormulaHelpers

#formula_any_version_installed?, #formula_opt_bin, #formula_opt_include, #formula_opt_lib, #formula_opt_libexec, #formula_opt_prefix

Methods included from OS::Linux::Keg

#change_rpath!, #elf_files

Constructor Details

#initialize(path) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'keg.rb', line 209

def initialize(path)
  path = resolved_path(path) if path.to_s.start_with?("#{HOMEBREW_PREFIX}/opt/")
  raise "#{path} is not a valid keg" if path.parent.parent.realpath != HOMEBREW_CELLAR.realpath
  raise "#{path} is not a directory" unless path.directory?

  @path = path
  @name = T.let(path.parent.basename.to_s, String)
  @linked_keg_record = T.let(HOMEBREW_LINKED_KEGS/name, Pathname)
  @opt_record = T.let(HOMEBREW_PREFIX/"opt/#{name}", Pathname)
  @oldname_opt_records = T.let([], T::Array[Pathname])
  @require_relocation = T.let(false, T::Boolean)
  @overwritten_cask_symlinks = T.let({}, T::Hash[Pathname, [String, Pathname]])
  @cask_symlink_tokens = T.let(nil, T.nilable(T::Hash[Pathname, String]))
end

Instance Attribute Details

#linked_keg_record ⇒ Pathname (readonly)

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



198
199
200
# File 'keg.rb', line 198

def linked_keg_record
  @linked_keg_record
end

#name ⇒ String (readonly)

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



195
196
197
# File 'keg.rb', line 195

def name
  @name
end

#opt_record ⇒ Pathname (readonly)

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



198
199
200
# File 'keg.rb', line 198

def opt_record
  @opt_record
end

Class Method Details

.all ⇒ Array<Keg>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



143
144
145
# File 'keg.rb', line 143

def self.all
  Formula.racks.flat_map(&:subdirs).map { |d| new(d) }
end

.each_candidate_string(file, string, &block) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Yields each printable string in the file with its hexadecimal offset, as strings -t x reports them. ELF files yield only the strings the loader or the program can reach, see elf_relocation_strings.

Parameters:



651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'keg_relocate.rb', line 651

def self.each_candidate_string(file, string, &block)
  if (elf_strings = elf_relocation_strings(file, string))
    elf_strings.each(&block)
    return
  end

  Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io|
    until io.eof?
      line = io.readline.chomp
      offset, match = line.split(" ", 2)
      odie "Failed to parse strings output: #{line.inspect}" if offset.nil? || match.nil?

      yield [offset, match]
    end
  end
end

.elf_dynamic_string_references(elf) ⇒ DynamicStringReferences?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

The strings the dynamic loader references in the file's dynamic string table, or nil without a dynamic segment or string table.

Parameters:

  • elf (ELFTools::ELFFile)

Returns:



775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# File 'keg_relocate.rb', line 775

def self.elf_dynamic_string_references(elf)
  dynamic = elf.segment_by_type(:dynamic)
  return if dynamic.nil?

  # Dynamic tags whose value is an offset into the dynamic string table,
  # i.e. the strings the loader can actually see.
  string_tags = [
    ELFTools::Constants::DT::DT_NEEDED,
    ELFTools::Constants::DT::DT_SONAME,
    ELFTools::Constants::DT::DT_RPATH,
    ELFTools::Constants::DT::DT_RUNPATH,
    ELFTools::Constants::DT::DT_AUXILIARY,
    # elftools 1.3.1 mislabels `DT_USED` (0x7ffffffe) as `DT_FILTER`;
    # both hold string-table offsets, so keep the mislabelled value
    # and add the ELF ABI's real `DT_FILTER`.
    ELFTools::Constants::DT::DT_FILTER,
    0x7fffffff, # DT_FILTER
    ELFTools::Constants::DT::DT_AUDIT,
    ELFTools::Constants::DT::DT_DEPAUDIT,
    ELFTools::Constants::DT::DT_CONFIG,
  ]
  string_table_vaddr = T.let(nil, T.nilable(Integer))
  string_table_size = T.let(nil, T.nilable(Integer))
  string_offsets = []
  dynamic.tags.each do |tag|
    case tag.header.d_tag.to_i
    when ELFTools::Constants::DT::DT_STRTAB then string_table_vaddr = tag.header.d_val.to_i
    when ELFTools::Constants::DT::DT_STRSZ then string_table_size = tag.header.d_val.to_i
    when *string_tags then string_offsets << tag.header.d_val.to_i
    end
  end
  return if string_table_vaddr.nil?

  string_table_offset = elf.offset_from_vma(string_table_vaddr)
  return if string_table_offset.nil?

  # Dynamic symbol names are loader-visible strings in the same table,
  # referenced by `.dynsym` `st_name` rather than by dynamic tags. Version
  # table strings also index the table but hold version names, never
  # paths, so they are not collected.
  elf.sections_by_type(ELFTools::Constants::SHT::SHT_DYNSYM).each do |section|
    section.symbols.each do |symbol|
      name_offset = symbol.header.st_name.to_i
      string_offsets << name_offset unless name_offset.zero?
    end
  end

  string_table_range = string_table_offset...(string_table_offset + string_table_size) if string_table_size
  DynamicStringReferences.new(string_table_range:,
                              offsets:            string_offsets.uniq.map { |offset| string_table_offset + offset })
end

.elf_relocation_strings(file, string) ⇒ Array<Array<(String, String)>>?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Build tools leave dead prefix strings in ELF files: Meson's install-time RPATH fixer overwrites the build RPATH with the shorter install RPATH without clearing the rest of the old string, and patchelf moves the dynamic string table or interpreter when growing them, leaving the old copy behind. A whole-file strings scan still finds those bytes and wrongly pins bottles whose live linkage is fully placeholdered. ELF files are therefore scanned by structure rather than as a whole: the interpreter the loader uses, the dynamic strings the loader references and the contents of the remaining sections. Bytes outside every section and unreferenced entries in loader-owned string tables are never candidates.

This deliberately errs towards relocatability (design decision 11 in plans/relocatable-bottles.md): a wrongly pinned bottle forces source builds for every non-default-prefix user, whereas a wrongly accepted one surfaces as a per-formula bug report and fix.

Returns nil, so that the whole file is scanned instead, for files that are not ELF, cannot name their sections or whose tables are truncated.

Parameters:

Returns:



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
# File 'keg_relocate.rb', line 691

def self.elf_relocation_strings(file, string)
  require "os/linux/elf"
  return unless T.cast(Pathname.new(file.to_s).extend(ELFShim), ELFShim).elf?

  require "elftools"
  require "strscan"

  stream = file.open("rb")
  begin
    elf = ELFTools::ELFFile.new(stream)
    # A file may legally keep section headers while `e_shstrndx` is
    # `SHN_UNDEF` (no section-name table); sections cannot be told apart
    # without names.
    return unless elf.section_name_table.is_a?(ELFTools::Sections::StrTabSection)

    strings = T.let([], T::Array[[Integer, String]])

    if (interp = elf.segment_by_type(:interp))
      strings << [interp.header.p_offset.to_i, interp.interp_name]
    end

    string_table_range = T.let(nil, T.nilable(T::Range[Integer]))
    if (references = elf_dynamic_string_references(elf))
      string_table_range = references.string_table_range
      referenced_offsets = references.offsets
      # A referenced string runs from its offset to the terminating NUL,
      # so a suffix-merged reference to the interior `libfoo.so` of
      # `/old/prefix/libfoo.so` never yields the dead prefix before it.
      referenced_offsets.each do |offset|
        stream.pos = offset
        referenced = stream.gets("\0")&.delete_suffix("\0")
        strings << [offset, referenced] if referenced
      end
    end

    # Everything else the program itself can reach: the contents of the
    # remaining sections. Loader-owned string regions are covered above and
    # bytes outside every section are deliberately excluded from relocation.
    elf.sections.each do |section|
      header = section.header
      # SHT_NOBITS sections (e.g. `.bss`) occupy no file bytes.
      next if header.sh_type.to_i == ELFTools::Constants::SHT::SHT_NOBITS
      next if header.sh_size.to_i.zero?
      next if [".dynstr", ".interp"].include?(section.name)

      section_start = header.sh_offset.to_i
      next if string_table_range&.cover?(section_start)

      data = section.data
      # Cheap pre-check before extracting every printable run.
      next unless data.include?(string)

      scanner = StringScanner.new(data)
      while scanner.skip_until(PRINTABLE_RUN_REGEX)
        run = scanner.matched
        strings << [section_start + scanner.pos - run.bytesize, run]
      end
    end

    strings.filter_map do |offset, match|
      next unless match.ascii_only?

      [offset.to_s(16), match.force_encoding(Encoding::UTF_8)]
    end
  ensure
    stream.close
  end
rescue ELFTools::ELFError, IOError, SystemCallError
  # Not valid ELF, or program, section or dynamic tables truncated or
  # pointing outside the file mid-parse (Linux raises `Errno::EINVAL`
  # for the resulting seek where macOS returns EOF).
  nil
end

.file_linked_libraries(_file, _string) ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



828
829
830
# File 'keg_relocate.rb', line 828

def self.file_linked_libraries(_file, _string)
  []
end

.for(path) ⇒ Keg

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • path (Pathname) —

    if this is a file in a keg, returns the containing Keg object.

Returns:

Raises:

  • (Errno::ENOENT)


120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'keg.rb', line 120

def self.for(path)
  original_path = path
  raise Errno::ENOENT, original_path.to_s unless original_path.exist?

  if (path = original_path.realpath)
    until path.root?
      return Keg.new(path) if path.parent.parent == HOMEBREW_CELLAR.realpath

      path = path.parent.realpath # realpath() prevents root? failing
    end
  end
  raise NotAKegError, "#{original_path} is not inside a keg"
end

.from_rack(rack) ⇒ Keg?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



135
136
137
138
139
140
# File 'keg.rb', line 135

def self.from_rack(rack)
  return unless rack.directory?

  kegs = rack.subdirs.map { |d| new(d) }
  kegs.find(&:linked?) || kegs.find(&:optlinked?) || kegs.max_by(&:scheme_and_version)
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



148
149
150
151
152
# File 'keg.rb', line 148

def self.keg_link_directories
  @keg_link_directories ||= T.let(%w[
    bin etc include lib sbin share var
  ].freeze, T.nilable(T::Array[String]))
end

.must_be_writable_directories ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Keep relatively in sync with https://github.com/Homebrew/install/blob/HEAD/install.sh

Returns:



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'keg.rb', line 174

def self.must_be_writable_directories
  @must_be_writable_directories ||= T.let((%w[
    etc/bash_completion.d lib/cps lib/pkgconfig
    share/aclocal share/doc share/info share/locale share/man
    share/man/man1 share/man/man2 share/man/man3 share/man/man4
    share/man/man5 share/man/man6 share/man/man7 share/man/man8
    share/cps share/zsh share/zsh/site-functions
    share/fish share/fish/vendor_completions.d share/fish/vendor_functions.d
    share/pwsh share/pwsh/completions
    var/log
  ].map { |dir| HOMEBREW_PREFIX/dir } + must_exist_subdirectories + [
    HOMEBREW_CACHE,
    HOMEBREW_CELLAR,
    HOMEBREW_LOCKS,
    HOMEBREW_LOGS,
    HOMEBREW_REPOSITORY,
    *HOMEBREW_PREFIX.glob("lib/python*/site-packages"),
  ]).sort.uniq.freeze, T.nilable(T::Array[Pathname]))
end

.must_exist_directories ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Keep relatively in sync with https://github.com/Homebrew/install/blob/HEAD/install.sh

Returns:



165
166
167
168
169
# File 'keg.rb', line 165

def self.must_exist_directories
  @must_exist_directories ||= T.let((must_exist_subdirectories + [
    HOMEBREW_CELLAR,
  ].sort.uniq).freeze, T.nilable(T::Array[Pathname]))
end

.must_exist_subdirectories ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



155
156
157
158
159
160
# File 'keg.rb', line 155

def self.must_exist_subdirectories
  @must_exist_subdirectories ||= T.let((keg_link_directories - %w[var] + %w[
    opt
    var/homebrew/linked
  ]).map { |dir| HOMEBREW_PREFIX/dir }.sort.uniq.freeze, T.nilable(T::Array[Pathname]))
end

.replace_prefix_preserving_length(string, old_prefix, new_prefix) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Pads path prefixes with separators to preserve string lengths and suffix offsets. Perl's module paths use compiled-in lengths, so trailing NULs become part of the path. Non-path occurrences cannot use separators: fall back to NUL padding with every occurrence replaced.

Parameters:

Returns:



454
455
456
457
458
459
460
461
# File 'keg_relocate.rb', line 454

def self.replace_prefix_preserving_length(string, old_prefix, new_prefix)
  padded = string.gsub(%r{#{Regexp.escape(old_prefix)}(?=[:/]|\z)}) do
    "#{new_prefix}#{"/" * (old_prefix.bytesize - new_prefix.bytesize)}"
  end
  return padded unless padded.include?(old_prefix)

  string.gsub(old_prefix) { new_prefix }.ljust(string.bytesize, NULL_BYTE)
end

.replace_x86_64_prefix!(binary, old_prefix, new_prefix) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Compilers can copy a path using successive movabs operands. Only replace complete prefixes in executable x86-64 ELF sections, keeping operand sizes.

Parameters:



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'keg_relocate.rb', line 412

def self.replace_x86_64_prefix!(binary, old_prefix, new_prefix)
  return unless binary.start_with?(ELF64_LITTLE_ENDIAN_MAGIC)

  require "elftools"
  require "stringio"

  elf = ELFTools::ELFFile.new(StringIO.new(binary))
  return if elf.header.e_machine.to_i != ELFTools::Constants::EM::EM_X86_64

  # Allow intervening stores and loads, but never skip another movabs.
  pattern = "#{old_prefix}/".b.bytes.each_slice(MOVABS_OPERAND_BYTESIZE).map do |bytes|
    chunk = bytes.pack("C*")
    "#{MOVABS_INSTRUCTION_REGEX}(#{Regexp.escape(chunk)}).{#{MOVABS_OPERAND_BYTESIZE - chunk.bytesize}}"
  end
  pattern = Regexp.new(pattern.join("(?:(?!#{MOVABS_INSTRUCTION_REGEX}).){0,#{MOVABS_MAX_GAP_BYTESIZE}}?"),
                       Regexp::MULTILINE | Regexp::NOENCODING)
  replacement = "#{new_prefix.b.ljust(old_prefix.bytesize, "/")}/"
  elf.sections.each do |section|
    next if section.header.sh_flags.to_i.nobits?(ELFTools::Constants::SHF::SHF_EXECINSTR)

    section.data.scan(pattern) do
      match = Regexp.last_match
      next if match.nil?

      match.captures.each_with_index do |chunk, index|
        offset = match.begin(index + 1)
        next if offset.nil?

        binary[section.header.sh_offset.to_i + offset, chunk.bytesize] =
          replacement.byteslice(index * MOVABS_OPERAND_BYTESIZE, chunk.bytesize).to_s
      end
    end
  end
rescue ELFTools::ELFError, IOError
  nil
end

.text_matches_in_file(file, string, ignores, linked_libraries, formula_and_runtime_deps_names) ⇒ Array<Array<(String, String)>>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'keg_relocate.rb', line 613

def self.text_matches_in_file(file, string, ignores, linked_libraries, formula_and_runtime_deps_names)
  text_matches = []
  path_regex = Relocation.path_to_regex(string)
  each_candidate_string(file, string) do |(offset, match)|
    next if ignores.any? { |i| match.match?(i) }
    next unless match.match? path_regex

    # Some binaries contain strings with lists of files
    # e.g. `/usr/local/lib/foo:/usr/local/share/foo:/usr/lib/foo`
    # Each item in the list should be checked separately
    match.split(":").each do |sub_match|
      # Not all items in the list may be matches
      next unless sub_match.match? path_regex
      next if linked_libraries.include? sub_match # Don't bother reporting a string if it was found by otool

      # Do not report matches to files that do not exist.
      next unless File.exist? sub_match

      # Do not report matches to build dependencies.
      if formula_and_runtime_deps_names.present?
        begin
          keg_name = Keg.for(Pathname.new(sub_match)).name
          next unless formula_and_runtime_deps_names.include? keg_name
        rescue NotAKegError
          nil
        end
      end

      text_matches << [match, offset] unless text_matches.any? { |text| text.last == offset }
    end
  end
  text_matches
end

Instance Method Details

#/(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


10
# File 'sorbet/rbi/dsl/keg.rbi', line 10

def /(*args, &block); end

#abv(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


13
# File 'sorbet/rbi/dsl/keg.rbi', line 13

def abv(*args, &block); end

#aliases ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



635
636
637
# File 'keg.rb', line 635

def aliases
  tab.aliases || []
end

#apps ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



450
451
452
453
# File 'keg.rb', line 450

def apps
  app_prefix = optlinked? ? opt_record : path
  Pathname.glob("#{app_prefix}/{,libexec/}*.app")
end

#binary_executable_or_library_files ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



771
772
773
# File 'keg.rb', line 771

def binary_executable_or_library_files
  []
end

#binary_file?(file) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:

  • (Boolean)


526
527
528
529
530
531
532
533
# File 'keg_relocate.rb', line 526

def binary_file?(file)
  grep_bin, grep_args = egrep_args

  # We need to pass NULL_BYTE_STRING, the literal string "\x00", to grep
  # rather than NULL_BYTE, a literal null byte, because grep will internally
  # convert the literal string "\x00" to a null byte.
  Utils.popen_read(grep_bin, *grep_args, NULL_BYTE_STRING, file).present?
end

#codesign_patched_binaries(files) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



779
# File 'keg.rb', line 779

def codesign_patched_binaries(files); end

#codesign_patched_binary(file) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



776
# File 'keg.rb', line 776

def codesign_patched_binary(file); end

#completion_installed?(shell) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:

  • (Boolean)


416
417
418
419
420
421
422
423
424
425
426
# File 'keg.rb', line 416

def completion_installed?(shell)
  dir = case shell
  when :bash then path/"etc/bash_completion.d"
  when :fish then path/"share/fish/vendor_completions.d"
  when :zsh
    dir = path/"share/zsh/site-functions"
    dir if dir.directory? && dir.children.any? { |f| f.basename.to_s.start_with?("_") }
  when :pwsh then path/"share/pwsh/completions"
  end
  !dir.nil? && dir.directory? && !dir.children.empty?
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



610
# File 'keg.rb', line 610

def consistent_reproducible_symlink_permissions!; end

#delete_node_gyp_debris! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'keg.rb', line 663

def delete_node_gyp_debris!
  # node-gyp compiles native addons inside the keg at install time and
  # leaves its intermediate objects and static archives behind; they embed
  # build paths that pin bottles and are never needed at run time (addons
  # load the linked `.node` files, not the objects they were linked from).
  # It always writes them into the package's `build` directory, so anything
  # matching elsewhere under `node_modules` is shipped by the package.
  path.find do |pn|
    next unless pn.to_s.include?("/node_modules/")
    next unless pn.to_s.include?("/build/")

    if pn.directory? && pn.basename.to_s == "obj.target"
      FileUtils.rm_rf pn
      Find.prune
    elsif %w[.o .d .a].include?(pn.extname) && pn.file?
      pn.delete
    end
  end
end

#delete_pyc_files! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



657
658
659
660
# File 'keg.rb', line 657

def delete_pyc_files!
  path.find { |pn| pn.delete if PYC_EXTENSIONS.include?(pn.extname) }
  path.find { |pn| FileUtils.rm_rf pn if pn.basename.to_s == "__pycache__" }
end

#detect_cxx_stdlibs(_options = {}) ⇒ Array<Symbol>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • _options (Hash{Symbol => Boolean}) (defaults to: {})

Returns:



464
465
466
# File 'keg_relocate.rb', line 464

def detect_cxx_stdlibs(_options = {})
  []
end

#directory?(*args, &block) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (Boolean)


16
# File 'sorbet/rbi/dsl/keg.rbi', line 16

def directory?(*args, &block); end

#disk_usage(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


19
# File 'sorbet/rbi/dsl/keg.rbi', line 19

def disk_usage(*args, &block); end

#each_unique_file_matching(string, &block) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



519
520
521
522
523
# File 'keg_relocate.rb', line 519

def each_unique_file_matching(string, &block)
  # Hardlinks share an inode with the file they point to, so only the first
  # name of each inode is yielded.
  files_matching_by_inode(string).map { |group| group.fetch(0) }.each(&block)
end

#egrep_args ⇒ Array<(String, Array<String>)>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



475
476
477
478
479
480
481
482
483
484
# File 'keg_relocate.rb', line 475

def egrep_args
  grep_bin = "grep"
  grep_args = [
    "--files-with-matches",
    "--perl-regexp",
    "--binary-files=text",
  ]

  [grep_bin, grep_args]
end

#elisp_installed? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


456
457
458
459
460
# File 'keg.rb', line 456

def elisp_installed?
  return false unless (path/"share/emacs/site-lisp"/name).exist?

  (path/"share/emacs/site-lisp"/name).children.any? { |f| ELISP_EXTENSIONS.include? f.extname }
end

#empty_installation? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'keg.rb', line 249

def empty_installation?
  Pathname.glob("#{path}/*") do |file|
    return false if file.directory? && file.children.any? { |child| child.basename.to_s != ".DS_Store" }

    basename = file.basename.to_s

    require "metafiles"
    next if Metafiles.copy?(basename)
    next if %w[.DS_Store INSTALL_RECEIPT.json].include?(basename)

    return false
  end

  true
end

#exist?(*args, &block) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (Boolean)


22
# File 'sorbet/rbi/dsl/keg.rbi', line 22

def exist?(*args, &block); end

#file_count(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


25
# File 'sorbet/rbi/dsl/keg.rbi', line 25

def file_count(*args, &block); end

#files_matching_by_inode(string) ⇒ Array<Array<Pathname>>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Files containing the string, grouped by inode so that hardlinks to the same file appear together.

Parameters:

Returns:



506
507
508
509
510
511
512
513
514
515
516
# File 'keg_relocate.rb', line 506

def files_matching_by_inode(string)
  files = T.let([], T::Array[Pathname])
  Utils.popen_read({ "LC_ALL" => "C" }, "fgrep", recursive_fgrep_args, string, to_s) do |io|
    until io.eof?
      file = Pathname.new(io.readline.chomp)
      # Don't return symbolic links.
      files << file unless file.symlink?
    end
  end
  files.group_by { |file| file.stat.ino }.values
end

#find(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


28
# File 'sorbet/rbi/dsl/keg.rbi', line 28

def find(*args, &block); end

#fix_dynamic_linkage ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



73
74
75
# File 'keg_relocate.rb', line 73

def fix_dynamic_linkage
  relativize_prefix_symlinks!
end

#functions_installed?(shell) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:

  • (Boolean)


429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'keg.rb', line 429

def functions_installed?(shell)
  case shell
  when :fish
    dir = path/"share/fish/vendor_functions.d"
    dir.directory? && !dir.children.empty?
  when :zsh
    # Check for non completion functions (i.e. files not started with an underscore),
    # since those can be checked separately
    dir = path/"share/zsh/site-functions"
    dir.directory? && dir.children.any? { |f| !f.basename.to_s.start_with?("_") }
  else
    false
  end
end

#homebrew_created_file?(file) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:

  • (Boolean)


238
239
240
241
242
# File 'keg_relocate.rb', line 238

def homebrew_created_file?(file)
  return false unless file.basename.to_s.start_with?("homebrew.", "sh.brew.")

  %w[.plist .service .timer].include?(file.extname)
end

#ignore_interrupts_and_uninstall! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



354
355
356
357
358
# File 'keg.rb', line 354

def ignore_interrupts_and_uninstall!
  Utils::Interrupts.ignore do
    uninstall
  end
end

#join(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


34
# File 'sorbet/rbi/dsl/keg.rbi', line 34

def join(*args, &block); end

#keepme_refs ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



763
764
765
766
767
768
# File 'keg.rb', line 763

def keepme_refs
  keepme = path/KEEPME_FILE
  return [] if !keepme.exist? || !keepme.readable?

  keepme.readlines.select { |ref| File.exist?(ref.strip) }
end

#keg_files(relative_paths) ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

The regular files the keg-relative paths recorded in bottle metadata refer to. Metadata may come from a mirror, so paths that would escape the keg (absolute, via .. or through a symlinked parent) are ignored rather than followed.

Parameters:

Returns:



491
492
493
494
495
496
497
498
499
500
501
# File 'keg_relocate.rb', line 491

def keg_files(relative_paths)
  keg_realpath = path.realpath
  relative_paths.filter_map do |relative_path|
    file = (path/relative_path).cleanpath
    next unless file.to_s.start_with?("#{path}/")
    next if file.symlink? || !file.file?
    next unless file.realpath.to_s.start_with?("#{keg_realpath}/")

    file
  end
end

#lib ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



536
537
538
# File 'keg_relocate.rb', line 536

def lib
  path/"lib"
end

#libexec ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



541
542
543
# File 'keg_relocate.rb', line 541

def libexec
  path/"libexec"
end

#libtool_files ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



588
589
590
591
592
593
594
595
596
597
# File 'keg_relocate.rb', line 588

def libtool_files
  libtool_files = []

  path.find do |pn|
    next if pn.symlink? || pn.directory? || Keg::LIBTOOL_EXTENSIONS.exclude?(pn.extname)

    libtool_files << pn
  end
  libtool_files
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • verbose (Boolean) (defaults to: false)
  • dry_run (Boolean) (defaults to: false)
  • overwrite (Boolean) (defaults to: false)

Returns:



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'keg.rb', line 498

def link(verbose: false, dry_run: false, overwrite: false)
  raise AlreadyLinkedError, self if linked_keg_record.directory?

  ObserverPathnameExtension.reset_counts!

  optlink(verbose:, dry_run:, overwrite:) unless dry_run

  # yeah indeed, you have to force anything you need in the main tree into
  # these dirs REMEMBER that *NOT* everything needs to be in the main tree
  link_dir("etc", verbose:, dry_run:, overwrite:) { :mkpath }
  link_dir("bin", verbose:, dry_run:, overwrite:) { :skip_dir }
  link_dir("sbin", verbose:, dry_run:, overwrite:) { :skip_dir }
  link_dir("include", verbose:, dry_run:, overwrite:) do |relative_path|
    case relative_path.to_s
    when /^postgresql@\d+/
      :mkpath
    else
      :link
    end
  end

  link_dir("share", verbose:, dry_run:, overwrite:) do |relative_path|
    case relative_path.to_s
    when INFOFILE_RX then :info
    when "locale/locale.alias",
         %r{^icons/.*/icon-theme\.cache$}
      :skip_file
    when LOCALEDIR_RX,
         %r{^icons/}, # all icons subfolders should also mkpath
         /^zsh/,
         /^fish/,
         /^pwsh/,
         %r{^lua/}, #  Lua, Lua51, Lua53 all need the same handling.
         %r{^guile/},
         /^postgresql@\d+/,
         /^pypy/,
         *SHARE_PATHS
      :mkpath
    else
      :link
    end
  end

  link_dir("lib", verbose:, dry_run:, overwrite:) do |relative_path|
    case relative_path.to_s
    when "charset.alias"
      :skip_file
    when "cps",       # Common Package Specification database gets explicitly created
         "pkgconfig", # pkg-config database gets explicitly created
         "cmake",     # cmake database gets explicitly created
         "dtrace",    # lib/language folders also get explicitly created
         /^gdk-pixbuf/,
         "ghc",
         /^gio/,
         /^lua/,
         /^mecab/,
         /^node/,
         /^ocaml/,
         /^perl5/,
         "php",
         /^postgresql@\d+/,
         /^pypy/,
         /^python[23]\.\d+/,
         /^R/,
         /^ruby/
      :mkpath
    else
      # Everything else is symlinked to the Cellar
      :link
    end
  end

  link_dir("Frameworks", verbose:, dry_run:, overwrite:) do |relative_path|
    # Frameworks contain symlinks pointing into a subdir, so we have to use
    # the :link strategy. However, for Foo.framework and
    # Foo.framework/Versions we have to use :mkpath so that multiple formulae
    # can link their versions into it and `brew [un]link` works.
    if relative_path.to_s.match?(%r{[^/]*\.framework(/Versions)?$})
      :mkpath
    else
      :link
    end
  end
  make_relative_symlink(linked_keg_record, path, verbose:, dry_run:, overwrite:) unless dry_run
  @overwritten_cask_symlinks.group_by { |_, (cask_token, _)| cask_token }.each do |cask_token, symlinks|
    opoo <<~EOS
      Overwrote symlinks from the #{cask_token} cask:
        #{symlinks.map(&:first).join("\n  ")}
      To restore them, run:
        brew unlink --formula #{name} && brew link --cask #{cask_token}
    EOS
  end
rescue => e
  raise if dry_run || e.is_a?(AlreadyLinkedError)

  unlink(verbose:)
  @overwritten_cask_symlinks.each do |dst, (_, source)|
    dst.dirname.mkpath
    FileUtils.ln_sf(source, dst)
  end
  raise
else
  ObserverPathnameExtension.n
ensure
  @overwritten_cask_symlinks.clear
  @cask_symlink_tokens = nil
end

#linked? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


274
275
276
277
278
# File 'keg.rb', line 274

def linked?
  linked_keg_record.symlink? &&
    linked_keg_record.directory? &&
    path == resolved_path(linked_keg_record)
end

#lock(&_block) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • _block (T.proc.void)


403
404
405
406
407
408
409
410
411
412
413
# File 'keg.rb', line 403

def lock(&_block)
  FormulaLock.new(name).with_lock do
    oldname_locks = oldname_opt_records.map do |record|
      FormulaLock.new(record.basename.to_s)
    end
    oldname_locks.each(&:lock)
    yield
  ensure
    oldname_locks&.each(&:unlock)
  end
end

#new_usr_local_replacement_pairs ⇒ Hash{Symbol => Hash{Symbol => String}}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'keg_relocate.rb', line 108

def new_usr_local_replacement_pairs
  {
    prefix:       {
      old: "/usr/local/opt",
      new: "#{PREFIX_PLACEHOLDER}/opt",
    },
    caskroom:     {
      old: "/usr/local/Caskroom",
      new: "#{PREFIX_PLACEHOLDER}/Caskroom",
    },
    etc_name:     {
      old: "/usr/local/etc/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/etc/#{name}",
    },
    var_homebrew: {
      old: "/usr/local/var/homebrew",
      new: "#{PREFIX_PLACEHOLDER}/var/homebrew",
    },
    var_www:      {
      old: "/usr/local/var/www",
      new: "#{PREFIX_PLACEHOLDER}/var/www",
    },
    var_name:     {
      old: "/usr/local/var/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/var/#{name}",
    },
    var_log_name: {
      old: "/usr/local/var/log/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/var/log/#{name}",
    },
    var_lib_name: {
      old: "/usr/local/var/lib/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/var/lib/#{name}",
    },
    var_run_name: {
      old: "/usr/local/var/run/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/var/run/#{name}",
    },
    var_db_name:  {
      old: "/usr/local/var/db/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/var/db/#{name}",
    },
    share_name:   {
      old: "/usr/local/share/#{name}",
      new: "#{PREFIX_PLACEHOLDER}/share/#{name}",
    },
  }
end

#normalize_pod2man_outputs! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
# File 'keg.rb', line 712

def normalize_pod2man_outputs!
  # Only process uncompressed manpages, which end in a digit
  manpages = Dir[path/"share/man/*/*.[1-9]{,p,pm}"]
  generated_regex = /^\.\\"\s*Automatically generated by .*\n/
  manpages.each do |f|
    manpage = Pathname.new(f)
    next unless manpage.file?

    content = manpage.read
    unless content.valid_encoding?
      # Occasionally, a manpage might not be encoded as UTF-8. ISO-8859-1 is a
      # common alternative that's worth trying in this case.
      content = File.read(manpage, encoding: "ISO-8859-1")

      # If the encoding is still invalid, we can't do anything about it.
      next unless content.valid_encoding?
    end

    content = content.gsub(generated_regex, "")
    content = content.lines.map do |line|
      if line.start_with?(".TH")
        # Split the line by spaces, but preserve quoted strings
        parts = line.split(/\s(?=(?:[^"]|"[^"]*")*$)/)
        next line if parts.length != 6

        # pod2man embeds the perl version used into the 5th field of the footer
        parts[4]&.gsub!(/^"perl v.*"$/, "\"\"")
        # man extension remove in man files
        parts[2]&.gsub!(/([1-9])(?:pm|p)?/, "\\1")

        "#{parts.join(" ")}\n"
      elsif line.start_with?(".IX")
        # Split the line by spaces, but preserve quoted strings
        parts = line.split(/\s(?=(?:[^"]|"[^"]*")*$)/)
        next line if parts.length != 3
        next line if parts[1] != "Title"

        # man extension remove in man files
        parts[2]&.gsub!(/([1-9])(?:pm|p)?/, "\\1")

        "#{parts.join(" ")}\n"
      else
        line
      end
    end.join

    manpage.atomic_write(content)
  end
end

#oldname_opt_records ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



485
486
487
488
489
490
491
492
493
494
495
# File 'keg.rb', line 485

def oldname_opt_records
  return @oldname_opt_records unless @oldname_opt_records.empty?

  @oldname_opt_records = if (opt_dir = HOMEBREW_PREFIX/"opt").directory?
    opt_dir.subdirs.select do |dir|
      dir.symlink? && dir != opt_record && path.parent == resolved_path(dir).parent
    end
  else
    []
  end
end

#openjdk_dep_name_if_applicable ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



229
230
231
232
233
234
235
# File 'keg_relocate.rb', line 229

def openjdk_dep_name_if_applicable
  deps = runtime_dependencies
  return if deps.blank?

  dep_names = deps.map { |d| d["full_name"] }
  dep_names.find { |d| d.match? Version.formula_optionally_versioned_regex(:openjdk) }
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • verbose (Boolean) (defaults to: false)
  • dry_run (Boolean) (defaults to: false)
  • overwrite (Boolean) (defaults to: false)


640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'keg.rb', line 640

def optlink(verbose: false, dry_run: false, overwrite: false)
  remove_old_aliases
  opt_record.delete if opt_record.symlink? || opt_record.exist?
  make_relative_symlink(opt_record, path, verbose:, dry_run:, overwrite:)
  aliases.each do |a|
    alias_opt_record = opt_record.parent/a
    alias_opt_record.delete if alias_opt_record.symlink? || alias_opt_record.exist?
    make_relative_symlink(alias_opt_record, path, verbose:, dry_run:, overwrite:)
  end

  oldname_opt_records.each do |record|
    record.delete
    make_relative_symlink(record, path, verbose:, dry_run:, overwrite:)
  end
end

#optlinked? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


287
288
289
# File 'keg.rb', line 287

def optlinked?
  opt_record.symlink? && path == resolved_path(opt_record)
end

#plist_installed? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


445
446
447
# File 'keg.rb', line 445

def plist_installed?
  !Dir["#{path}/*.plist"].empty?
end

#prepare_debug_symbols ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



607
# File 'keg.rb', line 607

def prepare_debug_symbols; end

#prepare_relocation_to_locations ⇒ Relocation

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'keg_relocate.rb', line 194

def prepare_relocation_to_locations
  relocation = Relocation.new
  relocation.add_replacement_pair(:prefix, PREFIX_PLACEHOLDER, HOMEBREW_PREFIX.to_s)
  relocation.add_replacement_pair(:cellar, CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s)
  relocation.add_replacement_pair(:repository, REPOSITORY_PLACEHOLDER, HOMEBREW_REPOSITORY.to_s)
  relocation.add_replacement_pair(:library, LIBRARY_PLACEHOLDER, HOMEBREW_LIBRARY.to_s)
  relocation.add_replacement_pair(:perl, PERL_PLACEHOLDER, "#{HOMEBREW_PREFIX}/opt/perl/bin/perl")
  if (openjdk = openjdk_dep_name_if_applicable)
    relocation.add_replacement_pair(:java, JAVA_PLACEHOLDER, "#{HOMEBREW_PREFIX}/opt/#{openjdk}/libexec")
  end

  relocation
end

#prepare_relocation_to_placeholders(new_usr_local_relocation: new_usr_local_relocation?) ) ⇒ Relocation

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • new_usr_local_relocation (Boolean) (defaults to: new_usr_local_relocation?) )

Returns:



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'keg_relocate.rb', line 158

def prepare_relocation_to_placeholders(new_usr_local_relocation: new_usr_local_relocation?)
  relocation = Relocation.new

  # Use selective HOMEBREW_PREFIX replacement when HOMEBREW_PREFIX=/usr/local
  # This avoids overzealous replacement of system paths when a script refers to e.g. /usr/local/bin
  if new_usr_local_relocation
    new_usr_local_replacement_pairs.each do |key, value|
      relocation.add_replacement_pair(key, value.fetch(:old), value.fetch(:new), path: true)
    end
  else
    relocation.add_replacement_pair(:prefix, HOMEBREW_PREFIX.to_s, PREFIX_PLACEHOLDER, path: true)
  end

  relocation.add_replacement_pair(:cellar, HOMEBREW_CELLAR.to_s, CELLAR_PLACEHOLDER, path: true)
  # when HOMEBREW_PREFIX == HOMEBREW_REPOSITORY we should use HOMEBREW_PREFIX for all relocations to avoid
  # being unable to differentiate between them.
  if HOMEBREW_PREFIX != HOMEBREW_REPOSITORY
    relocation.add_replacement_pair(:repository, HOMEBREW_REPOSITORY.to_s, REPOSITORY_PLACEHOLDER, path: true)
  end
  relocation.add_replacement_pair(:library, HOMEBREW_LIBRARY.to_s, LIBRARY_PLACEHOLDER, path: true)
  relocation.add_replacement_pair(:perl,
                                  %r{\A#![ \t]*(?:/usr/bin/perl\d\.\d+|#{HOMEBREW_PREFIX}/opt/perl/bin/perl)( |$)}o,
                                  "#!#{PERL_PLACEHOLDER}\\1")
  relocation.add_replacement_pair(:java, JAVA_REGEX, JAVA_PLACEHOLDER)

  relocation
end

#rack ⇒ Pathname

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



225
226
227
# File 'keg.rb', line 225

def rack
  path.parent
end

#recursive_fgrep_args ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



469
470
471
472
# File 'keg_relocate.rb', line 469

def recursive_fgrep_args
  # for GNU grep; overridden for BSD grep on OS X
  "-lr"
end

#relativize_prefix_symlinks!(prefix: HOMEBREW_PREFIX.to_s, cellar: HOMEBREW_CELLAR.to_s) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Relocation never rewrites symlink targets, so make absolute symlinks into the given prefix or cellar relative to keep them resolving anywhere.

Parameters:

  • prefix (String) (defaults to: HOMEBREW_PREFIX.to_s)
  • cellar (String) (defaults to: HOMEBREW_CELLAR.to_s)


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'keg_relocate.rb', line 80

def relativize_prefix_symlinks!(prefix: HOMEBREW_PREFIX.to_s, cellar: HOMEBREW_CELLAR.to_s)
  symlink_files.each do |file|
    link = file.readlink
    # Don't fix relative symlinks
    next unless link.absolute?

    target = if link.to_s.start_with?("#{cellar}/")
      HOMEBREW_CELLAR/link.to_s.delete_prefix("#{cellar}/")
    elsif link.to_s.start_with?("#{prefix}/")
      HOMEBREW_PREFIX/link.to_s.delete_prefix("#{prefix}/")
    end
    next if target.nil?

    new_src = target.relative_path_from(file.parent)
    file.unlink
    FileUtils.ln_s(new_src, file)
  end
end

#relocate_build_prefix(keg, old_prefix, new_prefix, files: nil) ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns the patched files relative to the keg.

Parameters:

Returns:



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'keg_relocate.rb', line 310

def relocate_build_prefix(keg, old_prefix, new_prefix, files: nil)
  if Sandbox.isolate_operation?
    return JSON.parse(
      Sandbox.operation("relocate_prefix", JSON.generate(path: path.to_s, keg: keg.path.to_s,
                                                         old_prefix: old_prefix.to_s, new_prefix: new_prefix.to_s,
                                                         files: files&.map(&:to_s)),
                        write_paths: [path, keg.path]),
    ).map { |file| Pathname(file) }
  end

  old_prefix = old_prefix.to_s
  new_prefix = new_prefix.to_s
  # A raw C string can only be replaced in place by an equal-or-shorter
  # string, so refuse before touching any file rather than failing midway.
  if new_prefix.bytesize > old_prefix.bytesize
    raise ArgumentError, "Cannot relocate build prefix #{old_prefix} to longer prefix #{new_prefix}"
  end

  # Older bottle metadata misses paths split across movabs operands.
  prefix_patterns = MOVABS_INSTRUCTION_PREFIXES.map do |instruction_prefix|
    "#{instruction_prefix}#{old_prefix.b.byteslice(0, MOVABS_OPERAND_BYTESIZE)}"
  end
  prefix_patterns << old_prefix.b if files.nil?

  # Hardlinked names share one inode: patch it once through the first name
  # and re-link the rest afterwards, as the patched file gets a new inode.
  inode_groups = files_matching_by_inode(prefix_patterns.join("\n"))
  if files
    candidates = keg_files(files) | inode_groups.flatten
    # Bottle metadata records one name per inode, so the other names of a
    # hardlinked file are only found by a walk; do that only when needed.
    hardlinked_inodes = candidates.select { |file| file.stat.nlink > 1 }.to_set { |file| file.stat.ino }
    unless hardlinked_inodes.empty?
      path.find do |file|
        next if file.symlink? || !file.file?

        candidates << file if hardlinked_inodes.include?(file.stat.ino)
      end
    end
    inode_groups = candidates.uniq.group_by { |file| file.stat.ino }.values
  end

  patched_groups = T.let([], T::Array[T::Array[Pathname]])
  inode_groups.each do |group|
    file = group.fetch(0)
    # Skip text files, which do not need length-preserving replacement.
    next unless keg.binary_file?(file)

    # Skip sharballs, which appear to break if patched.
    next if Utils::Path.text_executable?(file)

    # Split binary by null characters into array and substitute new prefix for old prefix.
    Utils::Path.ensure_writable(file) do
      binary = File.binread file
      binary_strings = binary.split(/#{NULL_BYTE}/o, -1)
      match_indices = binary_strings.each_index.select do |i|
        binary_string = binary_strings.fetch(i)
        next false unless binary_string.include?(old_prefix)
        next false if binary_string.bytesize > MAX_C_STRING_BYTESIZE

        text = String.new(binary_string, encoding: Encoding::UTF_8)
        text.valid_encoding? && text.match?(C_STRING_REGEX)
      end

      match_indices.each do |i|
        binary_strings[i] = Keg.replace_prefix_preserving_length(binary_strings.fetch(i), old_prefix, new_prefix)
      end

      # Rejoin strings by null bytes.
      patched_binary = binary_strings.join(NULL_BYTE)
      Keg.replace_x86_64_prefix!(patched_binary, old_prefix, new_prefix)
      next if patched_binary == binary

      odebug "Replacing build prefix in: #{file}"
      if patched_binary.bytesize != binary.bytesize
        raise <<~EOS
          Patching failed!  Original and patched binary sizes do not match.
          Original size: #{binary.bytesize}
          Patched size: #{patched_binary.bytesize}
        EOS
      end

      file.atomic_write patched_binary
      patched_groups << group
    end
  end

  # Each patch broke the file's signature, so re-sign each patched file
  # exactly once, parallelised across files.
  codesign_patched_binaries(patched_groups.map { |group| group.fetch(0) })

  patched_groups.each do |group|
    first = group.fetch(0)
    group.drop(1).each { |file| FileUtils.ln(first, file, force: true) }
  end

  patched_groups.flatten.map { |file| file.relative_path_from(path) }
end

#relocate_dynamic_linkage(_relocation, with_placeholders: false, files: nil) ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • _relocation (Relocation)
  • with_placeholders (Boolean) (defaults to: false)
  • files (Array<Pathname>, nil) (defaults to: nil)

Returns:



103
# File 'keg_relocate.rb', line 103

def relocate_dynamic_linkage(_relocation, with_placeholders: false, files: nil) = []

#remove_linked_keg_record ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



281
282
283
284
# File 'keg.rb', line 281

def remove_linked_keg_record
  linked_keg_record.unlink
  rmdir_if_possible(linked_keg_record.parent)
end

#remove_old_aliases(versioned_aliases: aliases) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • versioned_aliases (Array<String>) (defaults to: aliases)


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'keg.rb', line 292

def remove_old_aliases(versioned_aliases: aliases)
  opt = opt_record.parent
  linkedkegs = linked_keg_record.parent

  if (tap = tab.tap)
    bad_tap_opt = opt/tap.user
    FileUtils.rm_rf bad_tap_opt if !bad_tap_opt.symlink? && bad_tap_opt.directory?
  end

  aliases.each do |a|
    # versioned aliases are handled below
    next if a.match?(/.+@./)

    remove_alias_symlink(opt/a, opt_record)
    remove_alias_symlink(linkedkegs/a, linked_keg_record)
  end

  Pathname.glob("#{opt_record}@*").each do |link|
    name = link.basename.to_s
    # Keep an alias this keg owns while its target is still installed.
    # A link that pointed at this keg is removed once that keg is gone.
    next if versioned_aliases.include?(name) && link.exist?

    remove_alias_symlink(link, rack, match_parent: true)
    remove_alias_symlink(linkedkegs/name, rack, match_parent: true)
  end
end

#remove_oldname_opt_records ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



613
614
615
616
617
618
619
620
621
# File 'keg.rb', line 613

def remove_oldname_opt_records
  oldname_opt_records.reject! do |record|
    next false if resolved_path(record) != path

    record.unlink
    rmdir_if_possible(record.parent)
    true
  end
end

#remove_opt_record ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



321
322
323
324
# File 'keg.rb', line 321

def remove_opt_record
  opt_record.unlink
  rmdir_if_possible(opt_record.parent)
end

#rename(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


37
# File 'sorbet/rbi/dsl/keg.rbi', line 37

def rename(*args, &block); end

#replace_locations_with_placeholders ⇒ Array<(Array<Pathname>, Array<Pathname>)>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



187
188
189
190
191
# File 'keg_relocate.rb', line 187

def replace_locations_with_placeholders
  relocation = prepare_relocation_to_placeholders.freeze
  linkage_files = relocate_dynamic_linkage(relocation, with_placeholders: true)
  [replace_text_in_files(relocation), linkage_files]
end

#replace_placeholders_with_locations(files, skip_linkage: false, linkage_files: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • files (Array<Pathname>, nil)
  • skip_linkage (Boolean) (defaults to: false)
  • linkage_files (Array<Pathname>, nil) (defaults to: nil)


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'keg_relocate.rb', line 212

def replace_placeholders_with_locations(files, skip_linkage: false, linkage_files: nil)
  if Sandbox.isolate_operation?
    require_relocation! if JSON.parse(Sandbox.operation(
                                        "relocate", JSON.generate(path: path.to_s, files: files&.map(&:to_s),
                                                                  skip_linkage:,
                                                                  linkage_files: linkage_files&.map(&:to_s)),
                                        write_paths: [path]
                                      ))
    return
  end

  relocation = prepare_relocation_to_locations.freeze
  relocate_dynamic_linkage(relocation, files: linkage_files) unless skip_linkage
  replace_text_in_files(relocation, files:)
end

#replace_text_in_files(relocation, files: nil) ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'keg_relocate.rb', line 245

def replace_text_in_files(relocation, files: nil)
  files ||= text_files | libtool_files

  changed_files = T.let([], T::Array[Pathname])
  keg_files(files).group_by { |f| f.stat.ino }.each_value do |hardlinks|
    first = hardlinks.fetch(0)
    rest = hardlinks.drop(1)
    s = first.open("rb", &:read)

    # Use full prefix replacement for Homebrew-created files when using selective relocation
    file_relocation = if new_usr_local_relocation? && homebrew_created_file?(first)
      prepare_relocation_to_placeholders(new_usr_local_relocation: false)
    else
      relocation
    end
    next unless file_relocation.replace_text!(s)

    changed_files += hardlinks.map { |file| file.relative_path_from(path) }

    begin
      first.atomic_write(s)
    rescue SystemCallError
      Utils::Path.ensure_writable(first) do
        first.open("wb") { |f| f.write(s) }
      end
    else
      rest.each { |file| FileUtils.ln(first, file, force: true) }
    end
  end
  changed_files
end

#require_relocation! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



269
270
271
# File 'keg.rb', line 269

def require_relocation!
  @require_relocation = true
end

#require_relocation? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


266
# File 'keg.rb', line 266

def require_relocation? = @require_relocation

#runtime_dependencies ⇒ Array<T.untyped>?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



629
630
631
632
# File 'keg.rb', line 629

def runtime_dependencies
  Keg.cache[:runtime_dependencies] ||= {}
  Keg.cache[:runtime_dependencies][path] ||= tab.runtime_dependencies
end

#scheme_and_version ⇒ Array<(Integer, PkgVersion)>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

For ordering kegs by version with .sort_by, .max_by, etc.

Returns:

See Also:



475
476
477
# File 'keg.rb', line 475

def scheme_and_version
  [version_scheme, version]
end

#strip_node_gyp_addons! ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'keg.rb', line 684

def strip_node_gyp_addons!
  strip = which("strip")
  return if strip.nil?

  stripped_files = []
  path.find do |pn|
    next if pn.symlink? || pn.extname != ".node" || pn.to_s.exclude?("/node_modules/")

    # node-gyp addons' `N_OSO`/`N_SO` stab strings embed keg build paths,
    # which pin bottles; stripping debug entries removes them.
    # Strip to a temporary file so a failure (e.g. an addon `strip` cannot
    # parse) leaves the addon untouched.
    stripped = Pathname("#{pn}.stripped")
    if SystemCommand.quiet_system(strip.to_s, "-S", "-o", stripped.to_s, pn.to_s)
      mode = pn.stat.mode
      FileUtils.mv stripped, pn
      pn.chmod mode
      stripped_files << pn
    else
      FileUtils.rm_f stripped
    end
  end

  # `strip -o` writes a new file instead of editing in place, so it never re-signs: reapply the ad-hoc signature.
  codesign_patched_binaries(stripped_files)
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



600
601
602
603
604
605
606
607
# File 'keg_relocate.rb', line 600

def symlink_files
  symlink_files = []
  path.find do |pn|
    symlink_files << pn if pn.symlink?
  end

  symlink_files
end

#tab ⇒ Tab

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



624
625
626
# File 'keg.rb', line 624

def tab
  Tab.for_keg(self)
end

#text_files ⇒ Array<Pathname>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'keg_relocate.rb', line 546

def text_files
  text_files = []
  return text_files if !which("file") || !which("xargs")

  files = Set.new path.find.reject { |pn|
    next true if pn.symlink?
    next true if pn.directory?
    next false if pn.basename.to_s == "orig-prefix.txt" # for python virtualenvs
    next true if pn == self/".brew/#{name}.rb"

    require "metafiles"
    next true if Metafiles::EXTENSIONS.include?(pn.extname)

    if Utils::Path.text_executable?(pn)
      text_files << pn
      next true
    end
    false
  }
  output, _status = Open3.capture2("xargs -0 file --no-dereference --print0",
                                   stdin_data: files.to_a.join("\0"))
  # `file` output sometimes contains data from the file, which may include
  # invalid UTF-8 entities, so tell Ruby this is just a bytestring
  output.force_encoding(Encoding::ASCII_8BIT)
  output.each_line do |line|
    path, info = line.split("\0", 2)
    # `file` sometimes prints more than one line of output per file;
    # subsequent lines do not contain a null-byte separator, so `info`
    # will be `nil` for those lines
    next unless info
    next unless info.include?("text")

    path = Pathname.new(path)
    next unless files.include?(path)

    text_files << path
  end

  text_files
end

#to_formula ⇒ Formula

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



480
481
482
# File 'keg.rb', line 480

def to_formula
  Formulary.from_keg(self)
end

#to_path(*args, &block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • args (T.untyped)
  • block (T.untyped)

Returns:

  • (T.untyped)


40
# File 'sorbet/rbi/dsl/keg.rbi', line 40

def to_path(*args, &block); end

#uninstall(raise_failures: false) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • raise_failures (Boolean) (defaults to: false)


327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'keg.rb', line 327

def uninstall(raise_failures: false)
  CacheStoreDatabase.use(:linkage) do |db|
    break unless db.created?

    LinkageCacheStore.new(path.to_s,
                          T.cast(db,
                                 CacheStoreDatabase[String, T::Hash[T.any(String, Symbol), T.anything]])).delete!
  end

  # Capture these before we delete the Tab.
  versioned_aliases = aliases
  FileUtils.rm_r(path)
  rmdir_if_possible(path.parent)
  remove_opt_record if optlinked?
  remove_linked_keg_record if linked?
  remove_old_aliases(versioned_aliases:)
  remove_oldname_opt_records
rescue Errno::EACCES, Errno::ENOTEMPTY
  raise if raise_failures

  odie <<~EOS
    Could not remove #{name} keg! Do so manually:
      sudo rm -rf #{path}
  EOS
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • verbose (Boolean) (defaults to: false)
  • dry_run (Boolean) (defaults to: false)

Returns:



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'keg.rb', line 361

def unlink(verbose: false, dry_run: false)
  ObserverPathnameExtension.reset_counts!

  dirs = []

  keg_directories = self.class.keg_link_directories.map { |d| path/d }.select(&:exist?)

  keg_directories.each do |dir|
    dir.find do |src|
      dst = HOMEBREW_PREFIX + src.relative_path_from(path)
      dst.extend(ObserverPathnameExtension)

      dirs << dst if dst.directory? && !dst.symlink?

      # check whether the file to be unlinked is from the current keg first
      next unless dst.symlink?
      next if src != resolved_path(dst)

      if dry_run
        puts dst
        Find.prune if src.directory?
        next
      end

      if dst.to_s.match?(INFOFILE_RX)
        Utils::Path.uninstall_info(dst, verbose: ObserverPathnameExtension.verbose?)
      end
      dst.unlink
      Find.prune if src.directory?
    end
  end

  unless dry_run
    remove_old_aliases
    remove_linked_keg_record if linked?
    (dirs - self.class.must_exist_subdirectories).reverse_each { |dir| rmdir_if_possible(dir) }
  end

  ObserverPathnameExtension.n
end

#version ⇒ PkgVersion

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



463
464
465
# File 'keg.rb', line 463

def version
  PkgVersion.parse(path.basename.to_s)
end

#version_scheme ⇒ Integer

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



468
469
470
# File 'keg.rb', line 468

def version_scheme
  @version_scheme ||= T.let(tab.version_scheme, T.nilable(Integer))
end