kkew3
11/26/2018 - 9:26 AM

Search for python virtualenv upwards from current directory till home directory, and source it if found. The virtualenv name is assumed to b

Search for python virtualenv upwards from current directory till home directory, and source it if found. The virtualenv name is assumed to be "rt".

#!/bin/bash
if [ "${BASH_SOURCE[0]}" = "\${0}" ]; then
	echo This script intends to be sourced rather than be called >> /dev/stderr
	exit 1
fi

__findrt_upward() {
	local acc=""
	local targetrt=""
	local venv="rt"  # virtualenv name to search for
	if [ -n "$1" ]; then expected_suffix="$1"; fi
	local targetrt=""

	# line 22-25 reverse the order of lines of stdin
	pwd \
	| tr '/' '\n' \
	| sed '/^ *$/d' \
	| while read pt; do
		acc="$acc/$pt"
		echo "$acc"
	done \
	| grep -n "" \
	| sed 's/^\([0-9]\+\):/\1 /' \
	| sort -k1 -nr \
	| sed 's/^\([0-9]\+\) //' \
	| while read pfx; do
		if [ "$pfx" = "$HOME" ]; then
			break
		fi
		if [ -f "$pfx/$venv/bin/activate" ]; then
			echo "$pfx/$venv/bin/activate"
			break
		fi
	done 
}

# don't do anything unless not in virtualenv
if [ -z "$VIRTUAL_ENV" ]; then
	__targetrt=$(__findrt_upward | head -1)
	if [ -f "$__targetrt" ]; then
		. "$__targetrt"
	else
		echo "virtualenv not found" >> /dev/stderr
	fi
	unset __targetrt
fi

unset __findrt_upward