Thursday, April 29, 2021

Show Git Branch in zsh

Doing a google search for setting the git branch in terminal will return a number or blogs or stackoverflow posts. The guide here at The Modern Coder is an easy guide to follow and really well explained. I took what Jack did and wrapped it into a script to set it for zsh on Mac OS. Similar to my script for setting Python3 as the default Python interpreter (it uses the same if statement for determining the shell).

# set rc file
SHELL=$(echo ${SHELL})
if [ ${SHELL} == "/bin/bash" ]; then
    RC="/Users/${USER}/.bashrc"
elif [ ${SHELL} == "/bin/zsh" ]; then
    RC="/Users/${USER}/.zshrc"
else
    echo "${SHELL} not supported"
fi

read -r -d '' SHOW_GIT_BRANCH <<'EOF'
    # Load version control information
    autoload -Uz vcs_info
    precmd() { vcs_info }
    # Format the vcs_info_msg_0_ variable
    zstyle ':vcs_info:git:*' formats 'on branch %b'
    # Set up the prompt (with git branch name)
    setopt PROMPT_SUBST
    PROMPT='%n in ${PWD/#$HOME/~} ${vcs_info_msg_0_} > '
EOF

GIT_BRANCH_SET=$(cat ${RC} | grep -q PROMPT=)
if [ ${?} == 1 ] && [ ${SHELL} == "/bin/zsh" ]; then
    echo ${SHOW_GIT_BRANCH} >> ${RC}
else
    echo "git shell settings already exist"
fi

This has been tested on a fresh install of macOS Big Sur (11.2.3). The script can also be pulled from a gist here on GitHub here. Hope this helps. If there are any issues or improvements please reach out.

Sunday, April 25, 2021

Set Python3 Default for Mac OS

With the deprecation of Python 2 and macOS shipping with it as the default, there are many guides on how to update it to Python 3. Following a guide here using Homebrew, I decided to put it into a script to run in case I needed to reinstall the operating system on my laptop. 

# install homebrew if not present; password required
HOMEBREW=$(which brew)
if [ ${HOMEBREW} == "" ]; then
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
else
    brew update && brew install python
fi

# set rc file
SHELL=$(echo ${SHELL})
if [ ${SHELL} == "/bin/bash" ]; then
    RC="/Users/${USER}/.bashrc"
elif [ ${SHELL} == "/bin/zsh" ]; then
    RC="/Users/${USER}/.zshrc"
else
    echo "${SHELL} not supported"
fi

# set alias for python to python3
PY_ALIAS="alias python=/usr/local/bin/python3"
ALIAS=$(cat ${RC} | grep -q python)
if [ ${?} == 1 ]; then
    echo ${PY_ALIAS} >> ${RC}
fi

This has been tested on a fresh install of macOS Big Sur (11.2.3), and will install homebrew if not present. It can be run for both bash and z-shell by setting the run commands file as a variable, then set the alias if it is not present. Hope this helps, if there are any issues or improvements please reach out. You can download the .sh file from a gist on GitHub here.