Posted on :: Updated on

Homebrew to wspaniały menadżer pakietów, z którego korzystam na macOS. Ponieważ staram się często aktualizować zainstalowane programy, to już nawykowo wpisuję do Terminala szereg komend w kolejności, czekając na jedną po drugiej. Bez sensu, marnowanie czasu, wzrost frustracji - od czego mam programowanie™?

Poniżej funkcja, którą wrzuciłem do pliku .bru.sh, a następnie podpiąłem w pliku .zshrc, o tak:

[[ -f ~/.bru.sh ]] && source ~/.bru.sh

Teraz wystarczy wpisać w Terminalu bru {-af} i litania robi się sama.

# ~/.bru.sh

function _verbose {
  local magenta=$'\e[35m'
  local clear=$'\e[0m'
  local command=${*}
  echo ${magenta}${command}${clear}
  bash -c "${command}"
}

function _ask {
  local message=${1}
  local yellow=$'\e[33m'
  local red=$'\e[31m'
  local clear=$'\e[0m'

  read -k1 "input?"${yellow}${message}${clear} && echo
  if [[ ${input} != [yY] ]]; then
    echo ${red}"Step skipped, continuing..."${clear}
    return 1
  fi
}

function _notify {
  local message=${1}
  local green=$'\e[32m'
  local clear=$'\e[0m'
  echo ${green}${message}${clear}
}

function _warn {
  local message=${1}
  local red=$'\e[31m'
  local clear=$'\e[0m'
  echo ${red}${message}${clear}
}

function bru {
  # Set default values
  local auto=false
  local full=false
  local ignored="firefox" # | separated

  # Parse options
  while getopts "af" opt; do
    case $opt in
    a) auto=true ;;
    f) full=true ;;
    \?) return 1 ;;
    esac
  done

  # Print warnings and notifications
  $auto && _warn "Automatic mode - won't ask for confirmation" ||
    _notify "Interactive mode - will ask for confirmation"
  $full && _warn "Full upgrade - includes ignored packages" ||
    _notify "Default upgrade - ignores specified packages"

  # Update and list outdated packages
  _verbose brew update

  _notify "Regular upgrade:"

  $full && _verbose brew outdated --formula ||
    _verbose "brew outdated --formula | grep -vE '($ignored)'"
  $full && _verbose brew outdated --cask ||
    _verbose "brew outdated --cask | grep -vE '($ignored)'"

  # Upgrade packages
  $auto || _ask "Regular upgrade? (y/n): " && {
    $full && _verbose "brew upgrade" ||
      _verbose "brew outdated | grep -vE '($ignored)' | xargs brew upgrade"
  }

  _notify "Greedy upgrade:"

  # List outdated greedy casks
  $full && _verbose brew outdated --cask --greedy ||
    _verbose "brew outdated --cask --greedy | grep -vE '($ignored)'"

  # Upgrade packages greedy
  $auto || _ask "Greedy upgrade? (y/n): " && {
    $full && _verbose "brew upgrade --greedy" ||
      _verbose "brew outdated --greedy | grep -vE '($ignored)' | xargs brew upgrade"
  }

  # Autoremove and cleanup
  _verbose brew autoremove
  _verbose brew cleanup
  _verbose brew doctor
}

Muzyczka podczas programowania:

M83 - Oblivion (feat Susanne Sundfør) - audio M83