homebrewpackage-managementdependency-tree

Uninstall a Homebrew package and everything that depends on it, recursively (aka uninstall dependents; uninstall rdepends; cascade removal)


For a CI task, I need to run a command in an environment where certain Homebrew packages are NOT present (in my case, openssl@1.1, openssl@3 and readline). These packages are preinstalled in the Github CI runner that I use, and many other preinstalled packages depend on them.

Though I can use brew uninstall --ignore-dependencies, this will break all the dependent packages which will break my CI job later if it happens to involve any of them. Though I can track that, too, that's not future-proof.

So I would rather like to uninstall the above packages AND everything that depends on them, recursively (effectively, the reverse of Uninstall / remove a Homebrew package including all its dependencies).

There doesn't seem to be a built-in brew subcommand for that. Since I'm probably not the first person with this task -- maybe there's a Homebrew plugin command? I couldn't find one.


Solution

  • I've written the following script, called it "brew-uninstall-cascade.sh":

    #!/bin/bash
    
    declare -a packages rdepends
    packages=("$@")
    
    # have to try one by one, otherwise `brew uses` would only print
    # packages that require them all rather than any of them
    for package in "${packages[@]}"; do
      rdepends+=($(brew uses --installed --include-build --include-test --include-optional --recursive "$package"))
    done
    brew uninstall "${packages[@]}" "${rdepends[@]}"