Class: Keg

Inherits:
Object
  • Object
show all
Extended by:
Cachable, Forwardable, T::Sig
Defined in:
extend/os/mac/keg.rb,
extend/os/mac/keg_relocate.rb,
extend/os/linux/keg_relocate.rb,
keg.rb,
os/mac/keg.rb,
keg_relocate.rb

Defined Under Namespace

Classes: AlreadyLinkedError, ConflictError, DirectoryNotWritableError, LinkError, Relocation

Constant Summary collapse

(remove_const :KEG_LINK_DIRECTORIES).freeze
%w[
  bin etc include lib sbin share var
].freeze
GENERIC_MUST_EXIST_SUBDIRECTORIES =
(remove_const :MUST_EXIST_SUBDIRECTORIES).freeze
MUST_EXIST_SUBDIRECTORIES =

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.

(
  KEG_LINK_DIRECTORIES - %w[var] + %w[
    opt
    var/homebrew/linked
  ]
).map { |dir| HOMEBREW_PREFIX/dir }.sort.uniq.freeze
GENERIC_MUST_EXIST_DIRECTORIES =
(remove_const :MUST_EXIST_DIRECTORIES).freeze
MUST_EXIST_DIRECTORIES =

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.

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

(MUST_EXIST_SUBDIRECTORIES + [
  HOMEBREW_CELLAR,
].sort.uniq).freeze
GENERIC_MUST_BE_WRITABLE_DIRECTORIES =
(remove_const :MUST_BE_WRITABLE_DIRECTORIES).freeze
MUST_BE_WRITABLE_DIRECTORIES =

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[
    etc/bash_completion.d 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/zsh share/zsh/site-functions
    var/log
  ].map { |dir| HOMEBREW_PREFIX/dir } + MUST_EXIST_SUBDIRECTORIES + [
    HOMEBREW_CACHE,
    HOMEBREW_CELLAR,
    HOMEBREW_LOCKS,
    HOMEBREW_LOGS,
    HOMEBREW_REPOSITORY,
    Language::Python.homebrew_site_packages,
  ]
).sort.uniq.freeze
FRAMEWORK_RX =

Matches framework references like XXX.framework/Versions/YYY/XXX and XXX.framework/XXX, both with or without a slash-delimited prefix.

%r{(?:^|/)(([^/]+)\.framework/(?:Versions/[^/]+/)?\2)$}.freeze
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]+(@.+)?)?}.freeze
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|dir)$}.freeze
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 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-info pixmaps sounds postgresql
].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
PREFIX_PLACEHOLDER =
"@@HOMEBREW_PREFIX@@"
CELLAR_PLACEHOLDER =
"@@HOMEBREW_CELLAR@@"
REPOSITORY_PLACEHOLDER =
"@@HOMEBREW_REPOSITORY@@"
LIBRARY_PLACEHOLDER =
"@@HOMEBREW_LIBRARY@@"
PERL_PLACEHOLDER =
"@@HOMEBREW_PERL@@"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Cachable

cache, clear_cache

Constructor Details

#initialize(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.

Returns a new instance of Keg.



168
169
170
171
172
173
174
175
176
177
178
# File 'keg.rb', line 168

def initialize(path)
  path = path.resolved_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 = path.parent.basename.to_s
  @linked_keg_record = HOMEBREW_LINKED_KEGS/name
  @opt_record = HOMEBREW_PREFIX/"opt/#{name}"
  @require_relocation = false
end

Instance Attribute Details

#linked_keg_recordObject (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.



158
159
160
# File 'keg.rb', line 158

def linked_keg_record
  @linked_keg_record
end

#nameObject (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.



158
159
160
# File 'keg.rb', line 158

def name
  @name
end

#opt_recordObject (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.



158
159
160
# File 'keg.rb', line 158

def opt_record
  @opt_record
end

Class Method Details

.allObject

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.



154
155
156
# File 'keg.rb', line 154

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

.bottle_dependenciesObject



92
93
94
95
96
97
98
99
100
101
102
103
# File 'extend/os/linux/keg_relocate.rb', line 92

def self.bottle_dependencies
  @bottle_dependencies ||= begin
    formulae = relocation_formulae
    gcc = Formulary.factory(CompilerSelector.preferred_gcc)
    if !Homebrew::EnvConfig.simulate_macos_on_linux? &&
       DevelopmentTools.non_apple_gcc_version("gcc") < gcc.version.to_i
      formulae += gcc.recursive_dependencies.map(&:name)
      formulae << gcc.name
    end
    formulae
  end
end

.file_linked_libraries(_file, _string) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'extend/os/mac/keg_relocate.rb', line 8

def file_linked_libraries(file, string)
  # Check dynamic library linkage. Importantly, do not perform for static
  # libraries, which will falsely report "linkage" to themselves.
  if file.mach_o_executable? || file.dylib? || file.mach_o_bundle?
    file.dynamically_linked_libraries.select { |lib| lib.include? string }
  else
    []
  end
end

.for(path) ⇒ Object

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

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

Raises:

  • (Errno::ENOENT)


140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'keg.rb', line 140

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

.relocation_formulaeObject



84
85
86
87
88
89
90
# File 'extend/os/linux/keg_relocate.rb', line 84

def self.relocation_formulae
  @relocation_formulae ||= if HOMEBREW_PATCHELF_RB_WRITE
    []
  else
    ["patchelf"]
  end.freeze
end

.text_matches_in_file(file, string, ignores, linked_libraries, formula_and_runtime_deps_names) ⇒ Object



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
276
277
278
279
280
281
282
# File 'keg_relocate.rb', line 245

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)
  Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io|
    until io.eof?
      str = io.readline.chomp
      next if ignores.any? { |i| i =~ str }
      next unless str.match? path_regex

      offset, match = str.split(" ", 2)

      # 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
  end
  text_matches
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

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.



191
192
193
# File 'keg.rb', line 191

def ==(other)
  instance_of?(other.class) && path == other.path
end

#aliasesObject

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.



504
505
506
# File 'keg.rb', line 504

def aliases
  tab.aliases || []
end

#apply_ad_hoc_signature(file) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'os/mac/keg.rb', line 64

def apply_ad_hoc_signature(file)
  return if MacOS.version < :big_sur
  return unless Hardware::CPU.arm?

  odebug "Codesigning #{file}"
  # Use quiet_system to squash notifications about resigning binaries
  # which already have valid signatures.
  return if quiet_system("codesign", "--sign", "-", "--force",
                         "--preserve-metadata=entitlements,requirements,flags,runtime",
                         file)

  # If the codesigning fails, it may be a bug in Apple's codesign utility
  # A known workaround is to copy the file to another inode, then move it back
  # erasing the previous file. Then sign again.
  #
  # TODO: remove this once the bug in Apple's codesign utility is fixed
  Dir::Tmpname.create("workaround") do |tmppath|
    FileUtils.cp file, tmppath
    FileUtils.mv tmppath, file, force: true
  end

  # Try signing again
  odebug "Codesigning (2nd try) #{file}"
  result = system_command("codesign", args: [
    "--sign", "-", "--force",
    "--preserve-metadata=entitlements,requirements,flags,runtime",
    file
  ], print_stderr: false)
  return if result.success?

  # If it fails again, error out
  onoe <<~EOS
    Failed applying an ad-hoc signature to #{file}:
    #{result.stderr}
  EOS
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:



378
379
380
381
# File 'keg.rb', line 378

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

#binary_executable_or_library_filesObject

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.



25
26
27
# File 'extend/os/mac/keg.rb', line 25

def binary_executable_or_library_files
  mach_o_files
end

#change_dylib_id(id, file) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'os/mac/keg.rb', line 5

def change_dylib_id(id, file)
  return if file.dylib_id == id

  @require_relocation = true
  odebug "Changing dylib ID of #{file}\n  from #{file.dylib_id}\n    to #{id}"
  MachO::Tools.change_dylib_id(file, id, strict: false)
  apply_ad_hoc_signature(file)
rescue MachO::MachOError
  onoe <<~EOS
    Failed changing dylib ID of #{file}
      from #{file.dylib_id}
        to #{id}
  EOS
  raise
end

#change_install_name(old, new, file) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'os/mac/keg.rb', line 21

def change_install_name(old, new, file)
  return if old == new

  @require_relocation = true
  odebug "Changing install name in #{file}\n  from #{old}\n    to #{new}"
  MachO::Tools.change_install_name(file, old, new, strict: false)
  apply_ad_hoc_signature(file)
rescue MachO::MachOError
  onoe <<~EOS
    Failed changing install name in #{file}
      from #{old}
        to #{new}
  EOS
  raise
end

#change_rpath(old, new, file) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'extend/os/linux/keg_relocate.rb', line 23

def change_rpath(file, old_prefix, new_prefix)
  return if !file.elf? || !file.dynamic_elf?

  updated = {}
  old_rpath = file.rpath
  new_rpath = if old_rpath
    rpath = old_rpath.split(":")
                     .map { |x| x.sub(old_prefix, new_prefix) }
                     .select { |x| x.start_with?(new_prefix, "$ORIGIN") }

    lib_path = "#{new_prefix}/lib"
    rpath << lib_path unless rpath.include? lib_path

    rpath.join(":")
  end
  updated[:rpath] = new_rpath if old_rpath != new_rpath

  old_interpreter = file.interpreter
  new_interpreter = if old_interpreter.nil?
    nil
  elsif File.readable? "#{new_prefix}/lib/ld.so"
    "#{new_prefix}/lib/ld.so"
  else
    old_interpreter.sub old_prefix, new_prefix
  end
  updated[:interpreter] = new_interpreter if old_interpreter != new_interpreter

  file.patch!(interpreter: updated[:interpreter], rpath: updated[:rpath])
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.

Returns:

  • (Boolean)


339
340
341
342
343
344
345
346
347
348
# File 'keg.rb', line 339

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

#delete_pyc_files!Object

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.



523
524
525
526
# File 'keg.rb', line 523

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

#delete_rpath(rpath, file) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'os/mac/keg.rb', line 53

def delete_rpath(rpath, file)
  odebug "Deleting rpath #{rpath} in #{file}"
  MachO::Tools.delete_rpath(file, rpath, strict: false)
  apply_ad_hoc_signature(file)
rescue MachO::MachOError
  onoe <<~EOS
    Failed deleting rpath #{rpath} in #{file}
  EOS
  raise
end

#detect_cxx_stdlibs(_options = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'extend/os/linux/keg_relocate.rb', line 53

def detect_cxx_stdlibs(options = {})
  skip_executables = options.fetch(:skip_executables, false)
  results = Set.new
  elf_files.each do |file|
    next unless file.dynamic_elf?
    next if file.binary_executable? && skip_executables

    dylibs = file.dynamically_linked_libraries
    results << :libcxx if dylibs.any? { |s| s.include? "libc++.so" }
    results << :libstdcxx if dylibs.any? { |s| s.include? "libstdc++.so" }
  end
  results.to_a
end

#dylib_id_for(file) ⇒ Object



102
103
104
105
106
107
108
# File 'extend/os/mac/keg_relocate.rb', line 102

def dylib_id_for(file)
  # The new dylib ID should have the same basename as the old dylib ID, not
  # the basename of the file itself.
  basename = File.basename(file.dylib_id)
  relative_dirname = file.dirname.relative_path_from(path)
  (opt_record/relative_dirname/basename).to_s
end

#each_linkage_for(file, linkage_type, &block) ⇒ Object



94
95
96
97
98
99
100
# File 'extend/os/mac/keg_relocate.rb', line 94

def each_linkage_for(file, linkage_type, &block)
  links = file.method(linkage_type)
              .call
              .uniq
              .reject { |fn| fn =~ /^@(loader_|executable_|r)path/ }
  links.each(&block)
end

#each_unique_file_matching(string) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
# File 'keg_relocate.rb', line 159

def each_unique_file_matching(string)
  Utils.popen_read("fgrep", recursive_fgrep_args, string, to_s) do |io|
    hardlinks = Set.new

    until io.eof?
      file = Pathname.new(io.readline.chomp)
      next if file.symlink?

      yield file if hardlinks.add? file.stat.ino
    end
  end
end

#elf_filesObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'extend/os/linux/keg_relocate.rb', line 67

def elf_files
  hardlinks = Set.new
  elf_files = []
  path.find do |pn|
    next if pn.symlink? || pn.directory?
    next if !pn.dylib? && !pn.binary_executable?

    # If we've already processed a file, ignore its hardlinks (which have the
    # same dev ID and inode). This prevents relocations from being performed
    # on a binary more than once.
    next unless hardlinks.add? [pn.stat.dev, pn.stat.ino]

    elf_files << pn
  end
  elf_files
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)


383
384
385
386
387
# File 'keg.rb', line 383

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)


197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'keg.rb', line 197

def empty_installation?
  Pathname.glob("#{path}/*") do |file|
    return false if file.directory? && !file.children.reject(&:ds_store?).empty?

    basename = file.basename.to_s
    next if Metafiles.copy?(basename)
    next if %w[.DS_Store INSTALL_RECEIPT.json].include?(basename)

    return false
  end

  true
end

#find_dylib(bad_name) ⇒ Object



133
134
135
136
137
138
# File 'extend/os/mac/keg_relocate.rb', line 133

def find_dylib(bad_name)
  return unless lib.directory?

  suffix = "/#{find_dylib_suffix_from(bad_name)}"
  lib.find { |pn| break pn if pn.to_s.end_with?(suffix) }
end

#find_dylib_suffix_from(bad_name) ⇒ Object



125
126
127
128
129
130
131
# File 'extend/os/mac/keg_relocate.rb', line 125

def find_dylib_suffix_from(bad_name)
  if (framework = bad_name.match(FRAMEWORK_RX))
    framework[1]
  else
    File.basename(bad_name)
  end
end

#fix_dynamic_linkageObject Also known as: generic_fix_dynamic_linkage



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'extend/os/mac/keg_relocate.rb', line 44

def fix_dynamic_linkage
  mach_o_files.each do |file|
    file.ensure_writable do
      change_dylib_id(dylib_id_for(file), file) if file.dylib?

      each_linkage_for(file, :dynamically_linked_libraries) do |bad_name|
        # Don't fix absolute paths unless they are rooted in the build directory
        next if bad_name.start_with?("/") &&
                !bad_name.start_with?(HOMEBREW_TEMP.to_s) &&
                !bad_name.start_with?(HOMEBREW_TEMP.realpath.to_s)

        new_name = fixed_name(file, bad_name)
        change_install_name(bad_name, new_name, file) unless new_name == bad_name
      end

      each_linkage_for(file, :rpaths) do |bad_name|
        # Strip rpaths rooted in the build directory
        next if !bad_name.start_with?(HOMEBREW_TEMP.to_s) &&
                !bad_name.start_with?(HOMEBREW_TEMP.realpath.to_s)

        delete_rpath(bad_name, file)
      end
    end
  end

  generic_fix_dynamic_linkage
end

#fixed_name(file, bad_name) ⇒ Object

If file is a dylib or bundle itself, look for the dylib named by bad_name relative to the lib directory, so that we can skip the more expensive recursive search if possible.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'extend/os/mac/keg_relocate.rb', line 75

def fixed_name(file, bad_name)
  if bad_name.start_with? PREFIX_PLACEHOLDER
    bad_name.sub(PREFIX_PLACEHOLDER, HOMEBREW_PREFIX)
  elsif bad_name.start_with? CELLAR_PLACEHOLDER
    bad_name.sub(CELLAR_PLACEHOLDER, HOMEBREW_CELLAR)
  elsif (file.dylib? || file.mach_o_bundle?) && (file.dirname/bad_name).exist?
    "@loader_path/#{bad_name}"
  elsif file.mach_o_executable? && (lib/bad_name).exist?
    "#{lib}/#{bad_name}"
  elsif file.mach_o_executable? && (libexec/"lib"/bad_name).exist?
    "#{libexec}/lib/#{bad_name}"
  elsif (abs_name = find_dylib(bad_name)) && abs_name.exist?
    abs_name.to_s
  else
    opoo "Could not fix #{bad_name} in #{file}"
    bad_name
  end
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.

Returns:

  • (Boolean)


350
351
352
353
354
355
356
357
358
359
360
361
# File 'keg.rb', line 350

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?("_") }
  end
end

#inspectString

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

def inspect
  "#<#{self.class.name}:#{path}>"
end

#libObject



172
173
174
# File 'keg_relocate.rb', line 172

def lib
  path/"lib"
end

#libexecObject



176
177
178
# File 'keg_relocate.rb', line 176

def libexec
  path/"libexec"
end

#libtool_filesObject



225
226
227
228
229
230
231
232
233
234
# File 'keg_relocate.rb', line 225

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.



406
407
408
409
410
411
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'keg.rb', line 406

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

  ObserverPathnameExtension.reset_counts!

  optlink(verbose: verbose, dry_run: dry_run, overwrite: 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: verbose, dry_run: dry_run, overwrite: overwrite) { :mkpath }
  link_dir("bin", verbose: verbose, dry_run: dry_run, overwrite: overwrite) { :skip_dir }
  link_dir("sbin", verbose: verbose, dry_run: dry_run, overwrite: overwrite) { :skip_dir }
  link_dir("include", verbose: verbose, dry_run: dry_run, overwrite: overwrite) { :link }

  link_dir("share", verbose: verbose, dry_run: dry_run, overwrite: 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/,
         %r{^lua/}, #  Lua, Lua51, Lua53 all need the same handling.
         %r{^guile/},
         *SHARE_PATHS
      :mkpath
    else
      :link
    end
  end

  link_dir("lib", verbose: verbose, dry_run: dry_run, overwrite: overwrite) do |relative_path|
    case relative_path.to_s
    when "charset.alias"
      :skip_file
    when "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",
         /^python[23]\.\d+/,
         /^R/,
         /^ruby/
      :mkpath
    else
      # Everything else is symlinked to the cellar
      :link
    end
  end

  link_dir("Frameworks", verbose: verbose, dry_run: dry_run, overwrite: 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
  unless dry_run
    make_relative_symlink(linked_keg_record, path, verbose: verbose, dry_run: dry_run, overwrite: overwrite)
  end
rescue LinkError
  unlink(verbose: verbose)
  raise
else
  ObserverPathnameExtension.n
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)


215
216
217
218
219
# File 'keg.rb', line 215

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

#lock(&block) ⇒ Object

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.



329
330
331
332
333
334
335
336
337
# File 'keg.rb', line 329

def lock(&block)
  FormulaLock.new(name).with_lock do
    if oldname_opt_record
      FormulaLock.new(oldname_opt_record.basename.to_s).with_lock(&block)
    else
      yield
    end
  end
end

#mach_o_filesObject



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'extend/os/mac/keg_relocate.rb', line 140

def mach_o_files
  hardlinks = Set.new
  mach_o_files = []
  path.find do |pn|
    next if pn.symlink? || pn.directory?
    next if !pn.dylib? && !pn.mach_o_bundle? && !pn.mach_o_executable?
    # if we've already processed a file, ignore its hardlinks (which have the same dev ID and inode)
    # this prevents relocations from being performed on a binary more than once
    next unless hardlinks.add? [pn.stat.dev, pn.stat.ino]

    mach_o_files << pn
  end

  mach_o_files
end

#oldname_opt_recordObject

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.



398
399
400
401
402
403
404
# File 'keg.rb', line 398

def oldname_opt_record
  @oldname_opt_record ||= if (opt_dir = HOMEBREW_PREFIX/"opt").directory?
    opt_dir.subdirs.find do |dir|
      dir.symlink? && dir != opt_record && path.parent == dir.resolved_path.parent
    end
  end
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.



508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'keg.rb', line 508

def optlink(verbose: false, dry_run: false, overwrite: false)
  opt_record.delete if opt_record.symlink? || opt_record.exist?
  make_relative_symlink(opt_record, path, verbose: verbose, dry_run: dry_run, overwrite: 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: verbose, dry_run: dry_run, overwrite: overwrite)
  end

  return unless oldname_opt_record

  oldname_opt_record.delete
  make_relative_symlink(oldname_opt_record, path, verbose: verbose, dry_run: dry_run, overwrite: overwrite)
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)


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

def optlinked?
  opt_record.symlink? && path == opt_record.resolved_path
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)


364
365
366
# File 'keg.rb', line 364

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

#prepare_relocation_to_locationsObject Also known as: generic_prepare_relocation_to_locations



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'extend/os/mac/keg_relocate.rb', line 156

def prepare_relocation_to_locations
  relocation = generic_prepare_relocation_to_locations

  brewed_perl = runtime_dependencies&.any? { |dep| dep["full_name"] == "perl" && dep["declared_directly"] }
  perl_path = if brewed_perl || name == "perl"
    "#{HOMEBREW_PREFIX}/opt/perl/bin/perl"
  elsif tab["built_on"].present?
    perl_path = "/usr/bin/perl#{tab["built_on"]["preferred_perl"]}"

    # For `:all` bottles, we could have built this bottle with a Perl we don't have.
    # Such bottles typically don't have strict version requirements.
    perl_path = "/usr/bin/perl#{MacOS.preferred_perl_version}" unless File.exist?(perl_path)

    perl_path
  else
    "/usr/bin/perl#{MacOS.preferred_perl_version}"
  end
  relocation.add_replacement_pair(:perl, PERL_PLACEHOLDER, perl_path)

  relocation
end

#prepare_relocation_to_placeholdersObject Also known as: generic_prepare_relocation_to_placeholders



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'keg_relocate.rb', line 85

def prepare_relocation_to_placeholders
  relocation = Relocation.new
  relocation.add_replacement_pair(:prefix, HOMEBREW_PREFIX.to_s, PREFIX_PLACEHOLDER, path: true)
  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#!(?:/usr/bin/perl\d\.\d+|#{HOMEBREW_PREFIX}/opt/perl/bin/perl)( |$)}o,
                                  "#!#{PERL_PLACEHOLDER}\\1")
  relocation
end

#python_pth_files_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)


373
374
375
# File 'keg.rb', line 373

def python_pth_files_installed?
  !Dir["#{path}/lib/python2.7/site-packages/*.pth"].empty?
end

#python_site_packages_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)


368
369
370
# File 'keg.rb', line 368

def python_site_packages_installed?
  (path/"lib/python2.7/site-packages").directory?
end

#rackObject

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.



180
181
182
# File 'keg.rb', line 180

def rack
  path.parent
end

#recursive_fgrep_argsObject Also known as: generic_recursive_fgrep_args



178
179
180
181
182
# File 'extend/os/mac/keg_relocate.rb', line 178

def recursive_fgrep_args
  # Don't recurse into symlinks; the man page says this is the default, but
  # it's wrong. -O is a BSD-grep-only option.
  "-lrO"
end

#relocate_dynamic_linkage(_relocation) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'extend/os/mac/keg_relocate.rb', line 21

def relocate_dynamic_linkage(relocation)
  mach_o_files.each do |file|
    file.ensure_writable do
      if file.dylib?
        id = relocated_name_for(file.dylib_id, relocation)
        change_dylib_id(id, file)
      end

      each_linkage_for(file, :dynamically_linked_libraries) do |old_name|
        new_name = relocated_name_for(old_name, relocation)
        change_install_name(old_name, new_name, file) if new_name
      end

      if ENV["HOMEBREW_RELOCATE_RPATHS"]
        each_linkage_for(file, :rpaths) do |old_name|
          new_name = relocated_name_for(old_name, relocation)
          change_rpath(old_name, new_name, file) if new_name
        end
      end
    end
  end
end

#relocated_name_for(old_name, relocation) ⇒ Object



110
111
112
113
114
115
116
117
118
119
# File 'extend/os/mac/keg_relocate.rb', line 110

def relocated_name_for(old_name, relocation)
  old_prefix, new_prefix = relocation.replacement_pair_for(:prefix)
  old_cellar, new_cellar = relocation.replacement_pair_for(:cellar)

  if old_name.start_with? old_cellar
    old_name.sub(old_cellar, new_cellar)
  elsif old_name.start_with? old_prefix
    old_name.sub(old_prefix, new_prefix)
  end
end

#remove_linked_keg_recordObject

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.



221
222
223
224
# File 'keg.rb', line 221

def remove_linked_keg_record
  linked_keg_record.unlink
  linked_keg_record.parent.rmdir_if_possible
end

#remove_old_aliasesObject

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.



230
231
232
233
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
# File 'keg.rb', line 230

def remove_old_aliases
  opt = opt_record.parent
  linkedkegs = linked_keg_record.parent

  tap = begin
    to_formula.tap
  rescue
    # If the formula can't be found, just ignore aliases for now.
    nil
  end

  if 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)
    remove_alias_symlink(linkedkegs/a, rack)
  end
end

#remove_oldname_opt_recordObject

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.



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

def remove_oldname_opt_record
  return unless oldname_opt_record
  return if oldname_opt_record.resolved_path != path

  @oldname_opt_record.unlink
  @oldname_opt_record.parent.rmdir_if_possible
  @oldname_opt_record = nil
end

#remove_opt_recordObject

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.



263
264
265
266
# File 'keg.rb', line 263

def remove_opt_record
  opt_record.unlink
  opt_record.parent.rmdir_if_possible
end

#replace_locations_with_placeholdersObject



102
103
104
105
106
# File 'keg_relocate.rb', line 102

def replace_locations_with_placeholders
  relocation = prepare_relocation_to_placeholders.freeze
  relocate_dynamic_linkage(relocation)
  replace_text_in_files(relocation)
end

#replace_placeholders_with_locations(files, skip_linkage: false) ⇒ Object



119
120
121
122
123
# File 'keg_relocate.rb', line 119

def replace_placeholders_with_locations(files, skip_linkage: false)
  relocation = prepare_relocation_to_locations.freeze
  relocate_dynamic_linkage(relocation) unless skip_linkage
  replace_text_in_files(relocation, files: files)
end

#replace_text_in_files(relocation, files: nil) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'keg_relocate.rb', line 125

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

  changed_files = []
  files.map(&path.method(:join)).group_by { |f| f.stat.ino }.each_value do |first, *rest|
    s = first.open("rb", &:read)

    next unless relocation.replace_text(s)

    changed_files += [first, *rest].map { |file| file.relative_path_from(path) }

    begin
      first.atomic_write(s)
    rescue SystemCallError
      first.ensure_writable 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?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)


211
212
213
# File 'keg.rb', line 211

def require_relocation?
  @require_relocation
end

#runtime_dependenciesObject

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.



499
500
501
502
# File 'keg.rb', line 499

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


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

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

  symlink_files
end

#tabObject

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.



495
496
497
# File 'keg.rb', line 495

def tab
  Tab.for_keg(self)
end

#text_filesObject



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'keg_relocate.rb', line 180

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

  # file has known issues with reading files on other locales. Has
  # been fixed upstream for some time, but a sufficiently new enough
  # file with that fix is only available in macOS Sierra.
  # https://bugs.gw.com/view.php?id=292
  with_custom_locale("C") do
    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"
      next true if Metafiles::EXTENSIONS.include?(pn.extname)

      if pn.text_executable?
        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
  end

  text_files
end

#to_formulaObject

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.



394
395
396
# File 'keg.rb', line 394

def to_formula
  Formulary.from_keg(self)
end

#uninstall(raise_failures: false) ⇒ Object

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.



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'keg.rb', line 268

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

    LinkageCacheStore.new(path, db).delete!
  end

  path.rmtree
  path.parent.rmdir_if_possible
  remove_opt_record if optlinked?
  remove_linked_keg_record if linked?
  remove_old_aliases
  remove_oldname_opt_record
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.



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

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

  dirs = []

  keg_directories = 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 != dst.resolved_path

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

      dst.uninstall_info if dst.to_s.match?(INFOFILE_RX)
      dst.unlink
      Find.prune if src.directory?
    end
  end

  unless dry_run
    remove_old_aliases
    remove_linked_keg_record if linked?
    dirs.reverse_each(&:rmdir_if_possible)
  end

  ObserverPathnameExtension.n
end

#versionObject

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.



389
390
391
392
# File 'keg.rb', line 389

def version
  require "pkg_version"
  PkgVersion.parse(path.basename.to_s)
end