From 546bc3f01d8fba90bd2a418ccc15027441a8ea8a Mon Sep 17 00:00:00 2001 From: Julien Palard Date: Sat, 2 Dec 2023 23:22:52 +0100 Subject: [PATCH] Make direnv use .venv/, show Python version in PS1. --- .bashrc | 61 ++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/.bashrc b/.bashrc index 27fbb43..df7489c 100644 --- a/.bashrc +++ b/.bashrc @@ -74,20 +74,48 @@ do fi done +trim() { + local var="$*" + # remove leading whitespace characters + var="${var#"${var%%[![:space:]]*}"}" + # remove trailing whitespace characters + var="${var%"${var##*[![:space:]]}"}" + printf '%s' "$var" +} + +shortest() +{ + # Returns the shortest of two strings + if [[ ${#1} -lt ${#2} ]] + then + printf "%s" "$1" + else + printf "%s" "$2" + fi + +} python_ps1() { - local pypath="$(which python 2>/dev/null)" - if [[ -z "$pypath" ]] || [[ "$pypath" == "/usr/bin/python" ]] - then + local relative venvpath pyversion _ + + venvpath="$(which python 2>/dev/null)" + venvpath="${venvpath%/bin/python}" + + if [[ -z "$venvpath" ]] || [[ "$venvpath" == "/usr" ]]; then return fi - local relative="$(realpath --relative-to=$(pwd) -s "$pypath")" - if [[ ${#relative} -lt ${#pypath} ]] - then - pypath="$relative" + + relative="$(realpath --relative-to="$(pwd)" -s "$venvpath")" + venvpath="$(shortest "$venvpath" "$relative")" + + if [[ "$venvpath" == ".venv" ]]; then + venvpath="" # No need to tell me my venv is in .venv, I can guess it. fi - printf "$1" "${pypath%/bin/python}" + + read -r _ pyversion <<<"$(python --version)" + + printf "$1" "$(trim "$venvpath $pyversion")" } if [[ "$TERM" != 'dumb' ]] @@ -203,21 +231,14 @@ e() venv() { - # direnv-first venv creation. - if [[ -f .envrc ]] - then - echo '`.envrc` file already exists!' - return - fi - echo "layout python3" > .envrc + # Simple helper to use direnv to create Python venvs. + # + # See https://github.com/pappasam/jedi-language-server/issues/199#issuecomment-1836880575 + # for more context. + printf "VIRTUAL_ENV=.venv\nlayout python3\n" > .envrc direnv allow . } -pip-common() -{ - python -m pip install --upgrade --upgrade-strategy eager mypy black flake8 jedi-language-server pylint build twine grip tox pip -} - github-gpg() { curl https://github.com/$1.gpg | gpg --import-options show-only --import -