1#!/bin/sh
2
3# Don't set -e because we don't have robust trapping and printing of errors.
4set -u
5
6# We use /bin/sh rather than /bin/bash for portability. See discussion here:
7# https://groups.google.com/forum/?nomobile=true#!topic/bazel-dev/4Ql_7eDcLC0
8# We do lose the ability to set -o pipefail.
9
10FAILURE_HEADER="\
11Error occurred while attempting to use the deprecated Python toolchain \
12(@rules_python//python/runtime_env_toolchain:all)."
13
14die() {
15  echo "$FAILURE_HEADER" 1>&2
16  echo "$1" 1>&2
17  exit 1
18}
19
20# We use `which` to locate the Python interpreter command on PATH. `command -v`
21# is another option, but it doesn't check whether the file it finds has the
22# executable bit.
23#
24# A tricky situation happens when this wrapper is invoked as part of running a
25# tool, e.g. passing a py_binary target to `ctx.actions.run()`. Bazel will unset
26# the PATH variable. Then the shell will see there's no PATH and initialize its
27# own, sometimes without exporting it. This causes `which` to fail and this
28# script to think there's no Python interpreter installed. To avoid this we
29# explicitly pass PATH to each `which` invocation. We can't just export PATH
30# because that would modify the environment seen by the final user Python
31# program.
32#
33# See also:
34#
35#     https://github.com/bazelbuild/continuous-integration/issues/578
36#     https://github.com/bazelbuild/bazel/issues/8414
37#     https://github.com/bazelbuild/bazel/issues/8415
38
39# Try the "python3" command name first, then fall back on "python".
40PYTHON_BIN="$(PATH="$PATH" which python3 2> /dev/null)"
41if [ -z "${PYTHON_BIN:-}" ]; then
42  PYTHON_BIN="$(PATH="$PATH" which python 2>/dev/null)"
43fi
44if [ -z "${PYTHON_BIN:-}" ]; then
45  die "Neither 'python3' nor 'python' were found on the target \
46platform's PATH, which is:
47
48$PATH
49
50Please ensure an interpreter is available on this platform (and marked \
51executable), or else register an appropriate Python toolchain as per the \
52documentation for py_runtime_pair \
53(https://github.com/bazelbuild/rules_python/blob/master/docs/python.md#py_runtime_pair)."
54fi
55
56exec "$PYTHON_BIN" "$@"
57
58