autoremove.rb 1.44 KB
Newer Older
Markus Reiter's avatar
Markus Reiter committed
1
# typed: true
Dawid Dziurla's avatar
Dawid Dziurla committed
2
3
4
5
# frozen_string_literal: true

require "formula"
require "cli/parser"
Tie's avatar
Tie committed
6
require "uninstall"
Dawid Dziurla's avatar
Dawid Dziurla committed
7
8
9
10
11
12
13
14
15

module Homebrew
  module_function

  def autoremove_args
    Homebrew::CLI::Parser.new do
      usage_banner <<~EOS
        `autoremove` [<options>]

Tie's avatar
Tie committed
16
        Uninstall formulae that were only installed as a dependency of another formula and are now no longer needed.
Dawid Dziurla's avatar
Dawid Dziurla committed
17
18
      EOS
      switch "-n", "--dry-run",
Tie's avatar
Tie committed
19
             description: "List what would be uninstalled, but do not actually uninstall anything."
EricFromCanada's avatar
EricFromCanada committed
20
21

      max_named 0
Dawid Dziurla's avatar
Dawid Dziurla committed
22
23
24
    end
  end

Tie's avatar
Tie committed
25
  def get_removable_formulae(formulae)
Tie's avatar
Tie committed
26
    removable_formulae = Formula.installed_formulae_with_no_dependents(formulae).reject do |f|
Tie's avatar
Tie committed
27
      Tab.for_keg(f.any_installed_keg).installed_on_request
Dawid Dziurla's avatar
Dawid Dziurla committed
28
29
    end

Tie's avatar
Tie committed
30
    removable_formulae += get_removable_formulae(formulae - removable_formulae) if removable_formulae.present?
Tie's avatar
Tie committed
31

Dawid Dziurla's avatar
Dawid Dziurla committed
32
33
34
35
36
37
    removable_formulae
  end

  def autoremove
    args = autoremove_args.parse

Tie's avatar
Tie committed
38
    removable_formulae = get_removable_formulae(Formula.installed)
Dawid Dziurla's avatar
Dawid Dziurla committed
39
40
    return if removable_formulae.blank?

Tie's avatar
Tie committed
41
    formulae_names = removable_formulae.map(&:full_name).sort
Dawid Dziurla's avatar
Dawid Dziurla committed
42

Tie's avatar
Tie committed
43
44
45
    verb = args.dry_run? ? "Would uninstall" : "Uninstalling"
    oh1 "#{verb} #{formulae_names.count} unneeded #{"formula".pluralize(formulae_names.count)}:"
    puts formulae_names.join("\n")
Dawid Dziurla's avatar
Dawid Dziurla committed
46
47
    return if args.dry_run?

Tie's avatar
Tie committed
48
    kegs_by_rack = removable_formulae.map(&:any_installed_keg).group_by(&:rack)
Tie's avatar
Tie committed
49
    Uninstall.uninstall_kegs(kegs_by_rack)
Dawid Dziurla's avatar
Dawid Dziurla committed
50
51
  end
end