From 9fe9fd7cd4ea07177c1a23dc3497cf089829cff2 Mon Sep 17 00:00:00 2001 From: Matan Rosenberg Date: Mon, 2 May 2022 16:49:16 +0300 Subject: [PATCH] Add pip shim --- shims/pip | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100755 shims/pip diff --git a/shims/pip b/shims/pip new file mode 100755 index 0000000..020a5f9 --- /dev/null +++ b/shims/pip @@ -0,0 +1,97 @@ +#! /usr/bin/env bash +# +# This script wraps pip to run `asdf reshim` after installs and uninstalls. +# Any other cases are passed-through to pip. +# +# Based on the npm shim: https://github.com/asdf-vm/asdf-nodejs/blob/b2d06a768d9a14186db72018df10604bdb384436/shims/npm + +set -euo pipefail + +this_dir=$(dirname "${BASH_SOURCE[0]}") +this_dir=$(cd "$this_dir" && pwd -P) # Normalizes the directory; see https://stackoverflow.com/a/7666/2308068 +plugin_name=$(basename "$(dirname "$this_dir")") + +asdf_data_dir=$(cd "${ASDF_DATA_DIR:-$HOME/.asdf}" && pwd -P) +asdf_shims_dir="$asdf_data_dir/shims" + +plugin_dir="$asdf_data_dir/plugins/$plugin_name" + +should_reshim() { + if [ "${ASDF_PYTHON_SKIP_RESHIM:-}" ]; then + return 1 + fi + + for arg; do + case "$arg" in + install|uninstall) + return 0 + ;; + esac + done + + return 1 +} + +resolve_pip() { + # Try searching in current path (asdf core from 0.7 onwards adds all binaries candidates directories to PATH) + # if that doesn't works (when calling the shim directly for example) it tries manually searching the binary in + # the installed version provided by "asdf where" + local pip_location="${ASDF_NODEJS_CANON_PIP_PATH:-$(search_pip_on_current_path || manually_search_pip_bin)}" + + if ! [ "$pip_location" ]; then + echo "asdf-python couldn't find a suitable pip executable" + echo "This is probably a problem with the plugin, please report this issue" + exit 1 + fi + + echo "$pip_location" +} + +remove_current_dir_from_path() { + local filtered_path= dir= normalized_dir= + + while read -rd : dir; do + if [ -d "$dir" ]; then + normalized_dir=$(cd "$dir" && pwd -P) + + if [ "$normalized_dir" = "$this_dir" ] || [ "$normalized_dir" = "$asdf_shims_dir" ]; then + continue + fi + fi + + filtered_path+="$dir:" + done <<< "$PATH:" + + echo "${filtered_path%:}" +} + +search_pip_on_current_path() { + # Tries to prevent recursion by removing the current script and asdf-shim from PATH + local filtered_path=$(remove_current_dir_from_path) + PATH="$filtered_path" command -v pip +} + +manually_search_pip_bin() { + local probably_pip="$(asdf where python)/bin/pip" + + if [ -x "$probably_pip" ]; then + echo "$probably_pip" + return 0 + fi + + return 1 +} + +wrap_pip() { + local pip=$(resolve_pip) + + if should_reshim "$@"; then + "$pip" "$@" + echo "Reshimming asdf $plugin_name..." + asdf reshim "$plugin_name" + else + exec "$pip" "$@" + fi +} + +wrap_pip "$@"