]> arthur.barton.de Git - ax-zsh.git/blob - plugins/homebrew/homebrew.zshrc
homebrew: Enhance code, no functional changes
[ax-zsh.git] / plugins / homebrew / homebrew.zshrc
1 # AX-ZSH: Alex' Modular ZSH Configuration
2 # homebrew.zshrc -- Setup Homebrew Package Manager
3
4 # Make sure that "brew(1)" is installed
5 (( $+commands[brew] )) || return 1
6
7 if [[ -n "$AXZSH_PLUGIN_CHECK" ]]; then
8         # Make sure brew command is working
9         brew --version >/dev/null 2>&1 || return 1
10 fi
11
12 function brew() {
13         # This wrapper function for the brew(1) command does the following:
14         # - Detect the location of the "real" brew(1) command.
15         # - Change user and group when the Homebrew installation is owned by a
16         #   different user (to preserve sane file permissions).
17         # - Set a relaxed umask(1) so that other users can use software
18         #   installed by Homebrew.
19         # - Call the "real" brew(1) command.
20
21         if [[ -x /home/linuxbrew/.linuxbrew/bin/brew ]]; then
22                 real_brew_cmd="/home/linuxbrew/.linuxbrew/bin/brew"
23         elif [[ -x /opt/homebrew/bin/brew ]]; then
24                 real_brew_cmd="/opt/homebrew/bin/brew"
25         elif [[ -x /usr/local/bin/brew ]]; then
26                 real_brew_cmd="/usr/local/bin/brew"
27         else
28                 if [[ "$1" != "shellenv" && "$1" != "--prefix" ]]; then
29                         echo "Oops, real \"brew\" command not found!? [for \"$1\"]" >&2
30                 fi
31                 return 101
32         fi
33
34         if [[ -z "$HOMEBREW_REPOSITORY" ]]; then
35                 eval "$("$real_brew_cmd" shellenv)"
36         fi
37
38         if [[ $(/bin/ls -ldn "$HOMEBREW_REPOSITORY" | awk '{print $3}') -eq $UID ]]; then
39                 # We are the owner of the Homebrew installation.
40                 (
41                         [[ $# -eq 0 && -t 1 ]] && echo "Running \"$real_brew_cmd\" ..."
42                         umask 0022 || return 103
43                         "$real_brew_cmd" "$@"
44                 )
45         else
46                 # We are a different user than the owner of the Homebrew
47                 # installation. So we need to change the user when running the
48                 # real "brew" command!
49                 priv_exec="umask 0022 || exit 103; \"$real_brew_cmd\" $*"
50                 (
51                         cd /tmp
52                         user="$(/bin/ls -ld "$HOMEBREW_REPOSITORY" | awk '{print $3}')"
53                         group="$(/bin/ls -ld "$HOMEBREW_REPOSITORY" | awk '{print $4}')"
54                         [[ $# -eq 0 && -t 1 ]] \
55                                 && echo "Running \"$real_brew_cmd\" as user \"$user:$group\" ..."
56                         sudo -u "$user" -g "$group" -- sh -c "$priv_exec"
57                 )
58         fi
59         return $?
60 }