bin/brew: avoid eval and grep

`eval` is a much bigger hammer than we need here, so let's try to avoid
that.

Also, we can use the builtin `read` instead of shelling out to `grep`
which will be slightly more efficient.
This commit is contained in:
Carlo Cabrera 2023-08-04 21:54:26 +08:00
parent 4877de52d3
commit bcbb969796
No known key found for this signature in database
GPG Key ID: C74D447FC549A1D0

View File

@ -78,28 +78,30 @@ unset BREW_FILE_DIRECTORY
HOMEBREW_LIBRARY="${HOMEBREW_REPOSITORY}/Library" HOMEBREW_LIBRARY="${HOMEBREW_REPOSITORY}/Library"
# Load Homebrew's variable configuration files from disk. # Load Homebrew's variable configuration files from disk.
export_homebrew_env_file() {
local env_file
env_file="${1}"
[[ -r "${env_file}" ]] || return 0
while read -r line
do
# only load HOMEBREW_* lines
[[ "${line}" = "HOMEBREW_"* ]] || continue
export "${line?}"
done <"${env_file}"
}
# First, load the system-wide configuration. # First, load the system-wide configuration.
if [[ -f "/etc/homebrew/brew.env" ]] unset SYSTEM_ENV_TAKES_PRIORITY
if [[ -n "${HOMEBREW_SYSTEM_ENV_TAKES_PRIORITY-}" ]]
then then
unset SYSTEM_ENV_TAKES_PRIORITY SYSTEM_ENV_TAKES_PRIORITY="1"
# only load HOMEBREW_*=* lines else
SYSTEM_HOMEBREW_ENV="$(grep -E '^HOMEBREW_[A-Z_]+=.*$' "/etc/homebrew/brew.env")" export_homebrew_env_file "/etc/homebrew/brew.env"
if [[ -n "${HOMEBREW_SYSTEM_ENV_TAKES_PRIORITY-}" ]]
then
SYSTEM_ENV_TAKES_PRIORITY="1"
else
eval "${SYSTEM_HOMEBREW_ENV}"
fi
fi fi
# Next, load the prefix configuration # Next, load the prefix configuration
if [[ -f "${HOMEBREW_PREFIX}/etc/homebrew/brew.env" ]] export_homebrew_env_file "${HOMEBREW_PREFIX}/etc/homebrew/brew.env"
then
# only load HOMEBREW_*=* lines
PREFIX_HOMEBREW_ENV="$(grep -E '^HOMEBREW_[A-Z_]+=.*$' "${HOMEBREW_PREFIX}/etc/homebrew/brew.env")"
eval "${PREFIX_HOMEBREW_ENV}"
unset PREFIX_HOMEBREW_ENV
fi
# Finally, load the user configuration # Finally, load the user configuration
if [[ -n "${XDG_CONFIG_HOME-}" ]] if [[ -n "${XDG_CONFIG_HOME-}" ]]
@ -129,20 +131,13 @@ else
exit 1 exit 1
fi fi
if [[ -f "${HOMEBREW_USER_CONFIG_HOME}/brew.env" ]] export_homebrew_env_file "${HOMEBREW_USER_CONFIG_HOME}/brew.env"
then
# only load HOMEBREW_*=* lines
USER_HOMEBREW_ENV="$(grep -E '^HOMEBREW_[A-Z_]+=.*$' "${HOMEBREW_USER_CONFIG_HOME}/brew.env")"
eval "${USER_HOMEBREW_ENV}"
unset USER_HOMEBREW_ENV
fi
# If the system configuration takes priority, load it last. # If the system configuration takes priority, load it last.
if [[ -n "${SYSTEM_ENV_TAKES_PRIORITY-}" ]] if [[ -n "${SYSTEM_ENV_TAKES_PRIORITY-}" ]]
then then
eval "${SYSTEM_HOMEBREW_ENV}" export_homebrew_env_file "/etc/homebrew/brew.env"
fi fi
unset SYSTEM_HOMEBREW_ENV
# Copy and export all HOMEBREW_* variables previously mentioned in # Copy and export all HOMEBREW_* variables previously mentioned in
# manpage or used elsewhere by Homebrew. # manpage or used elsewhere by Homebrew.