Skip to content

Commit ddce723

Browse files
keithcopybara-github
authored andcommitted
Avoid exporting PATH unnecessarily
This is a modification of PR bazelbuild#8415, which changed `which` to `command -v` so it works when PATH isn't exported. `command` is more standard for this kind of use case (https://github.com/koalaman/shellcheck/wiki/SC2230). Unfortunately, `command -v` doesn't check the executable bit, so it's not as useful for us. The previous fix for this issue (bazelbuild@7f49531) was based on exporting PATH, but this changes the environment seen by the exec'd payload Python code. The solution in this commit is to not export PATH but rather explicitly pass it to each invocation of `which`. Fixes bazelbuild#8414. See also bazelbuild/continuous-integration#578. Closes bazelbuild#8415. PiperOrigin-RevId: 249334274
1 parent b7a9615 commit ddce723

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

tools/python/pywrapper_template.txt

+20-8
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,30 @@ die() {
1515
exit 1
1616
}
1717

18-
# Make sure PATH is exported. If we're called with PATH unset, as happens when
19-
# we're invoked as a tool during the build, the shell will initialize its own
20-
# PATH but not necessarily export it. This would break our call to `which`. See
21-
# https://github.com/bazelbuild/continuous-integration/issues/578 for more
22-
# information.
23-
export PATH
18+
# We use `which` to locate the Python interpreter command on PATH. `command -v`
19+
# is another option, but it doesn't check whether the file it finds has the
20+
# executable bit.
21+
#
22+
# A tricky situation happens when this wrapper is invoked as part of running a
23+
# tool, e.g. passing a py_binary target to `ctx.actions.run()`. Bazel will unset
24+
# the PATH variable. Then the shell will see there's no PATH and initialize its
25+
# own, sometimes without exporting it. This causes `which` to fail and this
26+
# script to think there's no Python interpreter installed. To avoid this we
27+
# explicitly pass PATH to each `which` invocation. We can't just export PATH
28+
# because that would modify the environment seen by the final user Python
29+
# program.
30+
#
31+
# See also:
32+
#
33+
# https://github.com/bazelbuild/continuous-integration/issues/578
34+
# https://github.com/bazelbuild/bazel/issues/8414
35+
# https://github.com/bazelbuild/bazel/issues/8415
2436

2537
# Try the "python%VERSION%" command name first, then fall back on "python".
26-
PYTHON_BIN=`which python%VERSION% || echo ""`
38+
PYTHON_BIN=`PATH="$PATH" which python%VERSION% || echo ""`
2739
USED_FALLBACK=0
2840
if [ -z "${PYTHON_BIN:-}" ]; then
29-
PYTHON_BIN=`which python || echo ""`
41+
PYTHON_BIN=`PATH="$PATH" which python || echo ""`
3042
USED_FALLBACK=1
3143
fi
3244
if [ -z "${PYTHON_BIN:-}" ]; then

0 commit comments

Comments
 (0)