]> arthur.barton.de Git - ax-zsh.git/blob - plugins/homebrew/homebrew.zshrc
homebrew: Add a wrapper function for the brew(1) command
[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         brew_prefix=$("$real_brew_cmd" --prefix) || return 102
35
36         if [[ $(stat -c %u "$brew_prefix") -eq $UID ]]; then
37                 # We are the owner of the Homebrew installation.
38                 (
39                         [[ $# -eq 0 && -t 1 ]] \
40                                 && echo "Running \"$real_brew_cmd\" ..."
41                         umask 0022 || return 103
42                         "$real_brew_cmd" "$@"
43                 )
44         else
45                 # We are a different user than the owner of the Homebew
46                 # installation. So we need to change the user when running the
47                 # real "brew" command!
48                 priv_exec="umask 0022 || exit 103; \"$real_brew_cmd\" $*"
49                 (
50                         cd /tmp
51                         user="$(stat -c %U "$brew_prefix")"
52                         group="$(stat -c %G "$brew_prefix")"
53                         [[ $# -eq 0 && -t 1 ]] \
54                                 && echo "Running \"$real_brew_cmd\" as user \"$user:$group\" ..."
55                         sudo -u "$user" -g "$group" -- sh -c "$priv_exec"
56                 )
57         fi
58         return $?
59 }