Mike McQuaid 7073258a6a
Speed up brew list
Similarly to have we have with other commands, use Bash to speed it up.

Before:
```
$ hyperfine "brew list"
Benchmark 1: brew list
  Time (mean ± σ):     559.9 ms ± 122.8 ms    [User: 176.2 ms, System: 126.2 ms]
  Range (min … max):   503.2 ms … 907.3 ms    10 runs
```

After:
```
$ hyperfine "brew list"
Benchmark 1: brew list
  Time (mean ± σ):     223.7 ms ±  31.9 ms    [User: 35.0 ms, System: 53.4 ms]
  Range (min … max):   198.1 ms … 302.4 ms    10
```

Petty after comparison because someone on Homebrew/discussions compared
them:
```
$ hyperfine "brew list" "pip3 list"
Benchmark 1: brew list
  Time (mean ± σ):     213.1 ms ±  22.8 ms    [User: 34.2 ms, System: 49.2 ms]
  Range (min … max):   191.2 ms … 272.3 ms    13 runs

Benchmark 2: pip3 list
  Time (mean ± σ):     271.7 ms ±   4.6 ms    [User: 191.9 ms, System: 40.0 ms]
  Range (min … max):   264.7 ms … 281.4 ms    10 runs

Summary
  brew list ran
    1.28 ± 0.14 times faster than pip3 list
```

---

While we're here, also add the `HOMEBREW_CASKROOM` environment variable
to make things a bit cleaner and use `--caskroom` in documentation.

Co-authored-by: Carlo Cabrera <30379873+carlocab@users.noreply.github.com>
2024-05-17 12:38:16 +09:00

78 lines
1.6 KiB
Bash

# does the quickest output of brew list possible for no named arguments.
# HOMEBREW_CELLAR, HOMEBREW_PREFIX are set by brew.sh
# shellcheck disable=SC2154
homebrew-list() {
case "$1" in
# check we actually have list and not e.g. listsomething
list) ;;
list*) return 1 ;;
*) ;;
esac
local ls_args=()
local formula=""
local cask=""
for arg in "$@"
do
case "${arg}" in
# check for flags passed to ls
-1 | -l | -r | -t) ls_args+=("${arg}") ;;
--formula | --formulae) formula=1 ;;
--cask | --casks) cask=1 ;;
# reject all other flags
-* | *) return 1 ;;
esac
done
local tty
if [[ -t 1 ]]
then
tty=1
fi
local error_string="LS_ERRORED"
if [[ -z "${cask}" && -d "${HOMEBREW_CELLAR}" ]]
then
if [[ -n "${tty}" && -z "${formula}" ]]
then
ohai "Formulae"
fi
local formula_output
formula_output="$(ls "${ls_args[@]}" "${HOMEBREW_CELLAR}" || echo "${error_string}")"
if [[ "${formula_output}" == "${error_string}" ]]
then
exit 1
elif [[ -n "${formula_output}" ]]
then
echo "${formula_output}"
fi
if [[ -n "${tty}" && -z "${formula}" ]]
then
echo
fi
fi
if [[ -z "${formula}" && -d "${HOMEBREW_CASKROOM}" ]]
then
if [[ -n "${tty}" && -z "${cask}" ]]
then
ohai "Casks"
fi
local cask_output
cask_output="$(ls "${ls_args[@]}" "${HOMEBREW_CASKROOM}" || echo "${error_string}")"
if [[ "${cask_output}" == "${error_string}" ]]
then
exit 1
elif [[ -n "${cask_output}" ]]
then
echo "${cask_output}"
fi
return 0
fi
}