Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Homebrew external command to remove a formula and its dependencies that are no longer used. Warning: Not all formulas declare all their dependencies.
# Install to /usr/local/Library/Homebrew/cmd/rmtree.rb
require 'keg'
require 'formula'
require 'shellwords'
module Homebrew
def rmtree
raise KegUnspecifiedError if ARGV.named.empty?
if not ARGV.force?
ARGV.named.each do |keg_name|
puts bash "brew uninstall #{keg_name}"
deps = bash "join <(brew leaves) <(brew deps #{keg_name})"
if deps.length > 0
puts "Found lingering dependencies"
puts deps.chomp
deps = deps.split("\n")
deps.each do |dep|
dep = dep.chomp
if !dep.empty?
# Check if anything currently installed uses the dependency
dep_deps = bash "brew uses --installed #{dep}"
dep_deps = dep_deps.chomp
if dep_deps.length > 0
puts "Not removing dependency #{dep} because other installed packages depend on it:"
puts dep_deps
else
# Nothing claims to depend on it
puts "Removing dependency #{dep}..."
puts bash "brew rmtree #{dep}"
end
end
end
else
puts "No dependencies left on system for #{keg_name}."
end
end
else
puts "--force is not supported."
end
rescue MultipleVersionsInstalledError => e
ofail e
puts "Use `brew rmtree --force #{e.name}` to remove all versions."
end
def bash(command)
escaped_command = Shellwords.escape(command)
return %x! bash -c #{escaped_command} !
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment