Class: Keg Private

Inherits:
Object show all
Extended by:
Cachable, 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 Cachable

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_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

#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:



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

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_recordPathname (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:



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

def linked_keg_record
  @linked_keg_record
end

#nameString (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:



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

def name
  @name
end

#opt_recordPathname (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:



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

def opt_record
  @opt_record
end

Class Method Details

.allArray<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:



616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# File 'keg_relocate.rb', line 616

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:



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'keg_relocate.rb', line 740

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_dynamic_string_references_in(file) ⇒ Array<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.

Absolute file offsets of the strings the dynamic loader references in the file's dynamic string table, or none for files that are not ELF or cannot be parsed.

Parameters:

Returns:



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

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

  require "elftools"
  file.open("rb") do |stream|
    elf_dynamic_string_references(ELFTools::ELFFile.new(stream))&.offsets || []
  end
rescue ELFTools::ELFError, IOError, SystemCallError
  []
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:



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# File 'keg_relocate.rb', line 656

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:



793
794
795
# File 'keg_relocate.rb', line 793

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_directoriesArray<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
# 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/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_directoriesArray<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_subdirectoriesArray<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, preserve_suffix_offsets:) ⇒ 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.

Replaces the prefix in a NUL-terminated string without changing its length. Trailing NUL padding is invisible to C string readers but shifts any suffix-merged reference into the string, so when the string has such references pad each occurrence with extra path separators instead, which path resolution ignores (// is /, as is a trailing /). An occurrence followed by anything else is not a path under the prefix and cannot be padded that way, so such strings fall back to NUL padding with every occurrence replaced rather than being left partly relocated.

Parameters:

  • string (String)
  • old_prefix (String)
  • new_prefix (String)
  • preserve_suffix_offsets (Boolean)

Returns:



402
403
404
405
406
407
408
409
410
# File 'keg_relocate.rb', line 402

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

  string.gsub(old_prefix) { new_prefix }.ljust(string.bytesize, NULL_BYTE)
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:



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
605
606
607
608
609
610
# File 'keg_relocate.rb', line 578

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

#aliasesArray<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:



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

def aliases
  tab.aliases || []
end

#appsArray<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:



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

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

#binary_executable_or_library_filesArray<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:



766
767
768
# File 'keg.rb', line 766

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)


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

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:



774
# File 'keg.rb', line 774

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:



771
# File 'keg.rb', line 771

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)


411
412
413
414
415
416
417
418
419
420
421
# File 'keg.rb', line 411

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.



605
# File 'keg.rb', line 605

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.



658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'keg.rb', line 658

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.



652
653
654
655
# File 'keg.rb', line 652

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:



429
430
431
# File 'keg_relocate.rb', line 429

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:



484
485
486
487
488
# File 'keg_relocate.rb', line 484

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_argsArray<(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:



440
441
442
443
444
445
446
447
448
449
# File 'keg_relocate.rb', line 440

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)


451
452
453
454
455
# File 'keg.rb', line 451

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)


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

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:



471
472
473
474
475
476
477
478
479
480
481
# File 'keg_relocate.rb', line 471

def files_matching_by_inode(string)
  files = T.let([], T::Array[Pathname])
  Utils.popen_read("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_linkagevoid

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.



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

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)


424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'keg.rb', line 424

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)


227
228
229
230
231
# File 'keg_relocate.rb', line 227

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.



349
350
351
352
353
# File 'keg.rb', line 349

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_refsArray<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:



758
759
760
761
762
763
# File 'keg.rb', line 758

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:



456
457
458
459
460
461
462
463
464
465
466
# File 'keg_relocate.rb', line 456

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

#libPathname

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:



501
502
503
# File 'keg_relocate.rb', line 501

def lib
  path/"lib"
end

#libexecPathname

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:



506
507
508
# File 'keg_relocate.rb', line 506

def libexec
  path/"libexec"
end

#libtool_filesArray<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:



553
554
555
556
557
558
559
560
561
562
# File 'keg_relocate.rb', line 553

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:



493
494
495
496
497
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
# File 'keg.rb', line 493

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)


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

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)


398
399
400
401
402
403
404
405
406
407
408
# File 'keg.rb', line 398

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_pairsHash{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:



107
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
# File 'keg_relocate.rb', line 107

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.



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
# File 'keg.rb', line 707

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_recordsArray<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:



480
481
482
483
484
485
486
487
488
489
490
# File 'keg.rb', line 480

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_applicableString?

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:



218
219
220
221
222
223
224
# File 'keg_relocate.rb', line 218

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)


635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# File 'keg.rb', line 635

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)


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

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)


440
441
442
# File 'keg.rb', line 440

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

#prepare_debug_symbolsvoid

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.



602
# File 'keg.rb', line 602

def prepare_debug_symbols; end

#prepare_relocation_to_locationsRelocation

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:



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

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:



157
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
# File 'keg_relocate.rb', line 157

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

#rackPathname

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:



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

def rack
  path.parent
end

#recursive_fgrep_argsString

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:



434
435
436
437
# File 'keg_relocate.rb', line 434

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)


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

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:



285
286
287
288
289
290
291
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
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
# File 'keg_relocate.rb', line 285

def relocate_build_prefix(keg, old_prefix, new_prefix, files: nil)
  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

  # 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 = if files
    # Metadata-driven pour: only the files recorded at bottle time carry raw
    # prefix strings, so skip the whole-keg scan.
    candidates = keg_files(files)
    # 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
    candidates.uniq.group_by { |file| file.stat.ino }.values
  else
    files_matching_by_inode(old_prefix)
  end

  patched_groups = T.let([], T::Array[T::Array[Pathname]])
  inode_groups.each do |group|
    file = group.fetch(0)
    # Skip files which are not binary, as they do not need null padding.
    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.
    # Null padding is added if the new string is too short.
    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

      # Bottle metadata records files pinned by any prefix, cellar or
      # repository reference, so a recorded file may not contain this
      # particular string and must not be rewritten or re-signed.
      next if match_indices.empty?

      odebug "Replacing build prefix in: #{file}"

      # Linkers merge a string with the suffix of another, so a string in
      # the dynamic string table can be referenced from its interior.
      interior_references = Keg.elf_dynamic_string_references_in(file)
      string_starts = T.let([], T::Array[Integer])
      binary_strings.reduce(0) do |start, binary_string|
        string_starts << start
        start + binary_string.bytesize + 1
      end

      match_indices.each do |i|
        binary_string = binary_strings.fetch(i)
        start = string_starts.fetch(i)
        preserve_suffix_offsets = interior_references.any? do |reference|
          reference > start && reference < start + binary_string.bytesize
        end
        binary_strings[i] = Keg.replace_prefix_preserving_length(binary_string, old_prefix, new_prefix,
                                                                 preserve_suffix_offsets:)
      end

      # Rejoin strings by null bytes.
      patched_binary = binary_strings.join(NULL_BYTE)
      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:



102
# File 'keg_relocate.rb', line 102

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

#remove_linked_keg_recordvoid

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.



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

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

#remove_old_aliasesvoid

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.



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

def remove_old_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 |a|
    a = a.basename.to_s
    next if aliases.include?(a)

    remove_alias_symlink(opt/a, rack, match_parent: true)
    remove_alias_symlink(linkedkegs/a, rack, match_parent: true)
  end
end

#remove_oldname_opt_recordsvoid

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.



608
609
610
611
612
613
614
615
616
# File 'keg.rb', line 608

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_recordvoid

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.



318
319
320
321
# File 'keg.rb', line 318

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_placeholdersArray<(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:



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

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)


211
212
213
214
215
# File 'keg_relocate.rb', line 211

def replace_placeholders_with_locations(files, skip_linkage: false, linkage_files: nil)
  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:



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'keg_relocate.rb', line 234

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.



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

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)


265
# File 'keg.rb', line 265

def require_relocation? = @require_relocation

#runtime_dependenciesArray<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:



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

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

#scheme_and_versionArray<(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:



470
471
472
# File 'keg.rb', line 470

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.



679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# File 'keg.rb', line 679

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:



565
566
567
568
569
570
571
572
# File 'keg_relocate.rb', line 565

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

  symlink_files
end

#tabTab

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:



619
620
621
# File 'keg.rb', line 619

def tab
  Tab.for_keg(self)
end

#text_filesArray<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:



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
# File 'keg_relocate.rb', line 511

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_formulaFormula

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
# File 'keg.rb', line 475

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)


324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'keg.rb', line 324

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

  FileUtils.rm_r(path)
  rmdir_if_possible(path.parent)
  remove_opt_record if optlinked?
  remove_linked_keg_record if linked?
  remove_old_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:



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
# File 'keg.rb', line 356

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

#versionPkgVersion

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:



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

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

#version_schemeInteger

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_scheme
  @version_scheme ||= T.let(tab.version_scheme, T.nilable(Integer))
end