From 1537ddcc64d3c02acf70f43d3d01abdfe160677f Mon Sep 17 00:00:00 2001 From: bretello Date: Sat, 11 Nov 2023 18:54:40 +0100 Subject: [PATCH] zsh: python: add -f flag to mkvenv - improve mkvenv with getopts option parsing - add -f flag to force recreation of venv Usage: ```bash mkvenv [-sf] [venv_name] ``` --- functions/python.zsh | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/functions/python.zsh b/functions/python.zsh index 3eb94ba..a332700 100644 --- a/functions/python.zsh +++ b/functions/python.zsh @@ -1,25 +1,44 @@ mkvenv(){ - local source_venv - if [[ $1 == "-s" ]]; then - source_venv=y + local source_venv force_create venv_name + while getopts "sf" opt; do + case $opt in + s|source) source_venv=y ;; + f|force) force_create=y ;; + *) echo "Unknown option: $opt"; return 1 ;; + esac + done + + echo "force=$force_create" + return + shift $(($OPTIND-1)) + if [[ -n $1 ]]; then + venv_name=$1 shift fi - # any arguments are passed on to the `venv` module as flags/arguments - if [[ -e .venv ]]; then - echo "$(color $RED Error:) $(color $BOLD .venv) already exists." >&2 - return 1 + # any other arguments are passed on to the `venv` module as flags/arguments + echo ${venv_name} + if [[ -e ${venv_name} ]]; then + if [[ -n ${force_create} ]]; then + if [[ -n $VIRTUAL_ENV ]]; then # deactivate venv if enabled + deactivate && info "Deactivated existing virtualenv" || red "Could not run deactivate"; + fi + rm -rf ${venv_name} && info "Deleted existing virtualenv" + else + echo "$(color $RED Error:) $(color $BOLD .venv) already exists. Run with -f to recreate it." >&2 + return 1 + fi fi - echo -n "Creating venv..." && python -m virtualenv $@ .venv || echo -e "Failed to create virtualenv. Is virtualenv installed? Try:\n $ pip install virtualenv" + info "Creating virtualenv ${venv_name}... " && python -m virtualenv $@ ${venv_name}|| echo -e "Failed to create virtualenv. Is virtualenv installed? Try:\n $ pip install virtualenv" if [[ -z ${source_venv} ]]; then - echo -n " done. Enable? [Y/n]" + echo -n " done. Enable? [Y/n] " read source_venv else echo "" fi if [[ $source_venv != "n" ]]; then - source .venv/bin/activate && echo -e " → $(color $BOLD Enabled!) 🐍 $(color $BOLD$PURPLE $(python --version | cut -d " " -f2 )) ($(color $BOLD$GREEN $(pip --version | cut -d " " -f -2)))" + source ${venv_name}/bin/activate && echo -e " → $(color $BOLD Enabled!) 🐍 $(color $BOLD$PURPLE $(python --version | cut -d " " -f2 )) ($(color $BOLD$GREEN $(pip --version | cut -d " " -f -2)))" fi }