Proteusiq / dotfiles

🦊 Waiting for the World to Change One Bytes
MIT License
1 stars 0 forks source link

Should we Activate #5

Closed Proteusiq closed 5 months ago

Proteusiq commented 5 months ago
   cd() {
       builtin cd "$@"
       if [ -f "venv/bin/activate" ]; then
           source venv/bin/activate
       fi
   }
Proteusiq commented 5 months ago

Or more complex:

cd() {
    local current_dir=$(pwd)
    builtin cd "$@" && {
        local new_dir=$(pwd)
        if [[ $current_dir == $new_dir/* ]]; then
            # We're moving up out of a subdirectory. Check for deactivation.
            if [ -n "$VIRTUAL_ENV" ] && [[ ! $new_dir == $VIRTUAL_ENV/* ]]; then
                deactivate 2>/dev/null
            fi
        fi

        # Check for activation in the new directory
        if [ -f "venv/bin/activate" ]; then
            source venv/bin/activate
        elif [ -f ".venv/bin/activate" ]; then
            source .venv/bin/activate
        fi
    }
}
Proteusiq commented 5 months ago

cd is very precious to mess with so:

# activate venv or .venv projects similar to deactivate
activate_venv() {
    local dir=$PWD
    local found=0

    while [[ "$dir" != "/" && $found -eq 0 ]]; do
        if [[ -f "$dir/venv/bin/activate" ]]; then
            source "$dir/venv/bin/activate"
            found=1
            break
        elif [[ -f "$dir/.venv/bin/activate" ]]; then
            source "$dir/.venv/bin/activate"
            found=1
            break
        else
            dir=$(dirname "$dir")
        fi
    done

    if [[ $found -eq 0 ]]; then
        echo "No Python virtual environment found."
    fi
}

alias activate=activate_venv