function brew_uninstall --description "Select packages to uninstall" set --local uninst_pkgs $argv if test (count $uninst_pkgs) -eq 0 set uninst_pkgs (brew leaves | eval "fzf $FZF_DEFAULT_OPTS --multi --header='[brew:uninstall]'") end if test (count $uninst_pkgs) -gt 0 echo "Determining package dependencies..." # Output is multiline with format "pkgname:" if no dependencies, otherwise "pkgname: dep1 dep2 dep3 ..." set --local brew_deps_installed (string collect (brew deps --installed)) # Accumulate uninst_pkgs and their transitive dependencies set --local uninst_pkgs_all $uninst_pkgs for bdi in $brew_deps_installed set --local pkg (string split ':' $bdi | head -n 1) set --local deps (string split ' ' (string split ':' $bdi | tail -n +2)) if contains -- $pkg $uninst_pkgs for dep in $deps if test -n $dep if not contains -- $dep $uninst_pkgs_all set uninst_pkgs_all $uninst_pkgs_all $dep end end end end end # Don't uninstall packages that are still dependencies of other packages set --local uninst_pkgs_final $uninst_pkgs_all for bdi in $brew_deps_installed set --local pkg (string split ':' $bdi | head -n 1) set --local deps (string split ' ' (string split ':' $bdi | tail -n +2)) if not contains -- $pkg $uninst_pkgs_all for dep in $deps if test -n $dep if set --local index (contains --index $dep $uninst_pkgs_final) set --erase uninst_pkgs_final[$index] end end end end end echo "Uninstalling: $uninst_pkgs_final" brew uninstall $uninst_pkgs_final end end