Skip to content
Snippets Groups Projects
setup-sphinx 2.33 KiB
#! /bin/sh

set -e # exit immediately on error

MIN_PYTHON="3.6.0"

if [ -f "sphinx-build" ]; then
	exit 0
fi

setup_sphinx() {
	path="$(which sphinx-build)"
	if [ -z "$path" ]; then
		echo "INTERNAL ERROR: setup_sphinx() called, but no sphinx-build is in our PATH"
		exit 1
	fi
	# If path is a subdirectory, make relative for portability
	path="${path#$(pwd)/}"
	echo "Using $("$path" --version 2>&1) from \"$path\""
	ln -s "$path" ./
	exit 0
}

version_to_num() {
	major="$(echo $1 | awk -F. '{print $1}')"
	minor="$(echo $1 | awk -F. '{print $2}')"
	revision="$(echo $1 | awk -F. '{print $3}')"
	fakeversion="$(expr $major '*' 1000000 + $minor '*' 1000 + $revision)"
	echo "$fakeversion"
}

python_version_okay() {
	pyversion="$(echo "$1" | grep -o '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*')"
	testver=$(version_to_num "$pyversion")
	minver=$(version_to_num "$MIN_PYTHON")
	test $minver -le $testver || return 1
	return 0
}

sphinx_okay() {
	# Do we have one at all?
	which sphinx-build > /dev/null || return 1
	possible="$(which sphinx-build)"

	shbang="$(head -n1 "$possible" | grep -i '#!.*python' )"
	# Does it point to something that might be Python?
	test -n "$shbang" || return 1

	python="${shbang#"#!"}"
	python="${python#" "}"

	# Can that Python be run at all?
	"$python" --version > /dev/null 2>&1|| return 1

	# Is that Python new enough?
	pyversion="$("$python" --version 2>&1)"
	python_version_okay "$pyversion" || return 1

	return 0
}

describe_final() {
	echo "Using $("./sphinx-build" --version) from \"$1\""
}

if sphinx_okay; then
	echo "Using existing Sphinx install"
	ln -s "$path" ./
	describe_final "$path"
	exit 0
fi

echo "Could not find existing, working, new enough Sphinx version. Trying to install in a virtual environment."

python=""
python_options="python3 python3.6 python"
for maybe in $python_options; do
	if python_version_okay "$("$maybe" --version 2>&1)"; then
		python="$maybe"
		break
	fi
done
if [ -z "$python" ]; then
	echo "ERROR: Could not find Python version $MIN_PYTHON or newer (I checed $python_options)"
	exit 1
fi

echo "Creating virtual environment"
"$python" -m venv sphinx-env
. sphinx-env/bin/activate
echo "Installing sphinx"
pip install sphinx --quiet
path="$(which sphinx-build)"
deactivate
cat > sphinx-build <<'END'
#! /bin/sh
. sphinx-env/bin/activate
exec sphinx-build "$@"
END
chmod a+x sphinx-build
describe_final "$path"