From fb53437e2a9b88a6be6a509902740a5d46eb7225 Mon Sep 17 00:00:00 2001 From: Cameron Reed Date: Fri, 8 Nov 2024 10:49:18 -0700 Subject: [PATCH] run and build functions for make/cmake/just/python and automatic venv activation/deactivation --- .zshrc | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/.zshrc b/.zshrc index c5b21d7..9f7e606 100644 --- a/.zshrc +++ b/.zshrc @@ -6,6 +6,10 @@ [[ $- != *i* ]] && return +RUN_CMD="" +BUILD_CMD="" + + CACHE_DIR=${XDG_CACHE_HOME:-$HOME/.cache} STATE_DIR=${XDG_STATE_HOME:-$HOME/.local/state} @@ -89,7 +93,9 @@ function set_prompt() { local colors=(${(@s:~:)PROMPT_COLORS}) local prefixes=(${(@s:~:)PROMPT_PREFIXES}) - local prefix='' + manage_environments + + local prefix="${environment}" for i in $(seq 1 "${#prefixes[@]}"); do prefix+="%F{${colors[$i]:-255}}${prefixes[$i]}%F{255} " done @@ -102,12 +108,85 @@ function set_prompt() { fi PROMPT="[${prefix}${user}${host} %1~]%(#.#.$) " + + unset environment } typeset -a precmd_functions precmd_functions+=(set_prompt) +function manage_environments() { + RUN_CMD="" + BUILD_CMD="" + + local dir=$(pwd) + local depth=0 + while [ "$dir" != '/' ] && [ "$depth" -lt 20 ]; do + if [ -f "$dir/justfile" ]; then + environment="just:$(basename $dir) " + RUN_CMD="just run" + BUILD_CMD="just build" + break + fi + + if [ -f "$dir/CMakeLists.txt" ] && [ -d "$dir/build" ]; then + environment="cmake:$(basename $dir) " + RUN_CMD="cmake --build $dir/build --target install" + BUILD_CMD="cmake --build $dir/build" + break + fi + + if [ -f "$dir/Makefile" ]; then + environment="make:$(basename $dir) " + RUN_CMD="make -C $dir run" + BUILD_CMD="make -C $dir" + break + fi + + if [ -f "$dir/venv/bin/activate" ]; then + if [ "$VIRTUAL_ENV" != "$dir/venv" ]; then + . "$dir/venv/bin/activate" + fi + environment="python:$(basename dir) " + + local pyfiles=($dir/*.py) + if [ -f "$dir/main.py" ]; then + RUN_CMD="python3 $dir/main.py" + elif [ "${#pyfiles}" -eq 1 ]; then + RUN_CMD="python3 ${pyfiles}" + fi + break + fi + + dir=$(dirname "$dir") + depth=$(( $depth + 1 )) + done + + if [ -n "$VIRTUAL_ENV" ] && [[ ! "$environment" =~ "python" ]]; then + deactivate + fi +} + + +function run() { + if [ -n "$RUN_CMD" ]; then + eval "$RUN_CMD" + else + printf "Nothing to do here\n" + fi +} + + +function build() { + if [ -n "$BUILD_CMD" ]; then + eval "$BUILD_CMD" + else + printf "Nothing to do here\n" + fi +} + + # Setup bookmarks BOOKMARKS_DIR="$HOME/bookmarks"