Skip to content

Commit

Permalink
Reintroduce support for Python 2.6 to python_stub_template
Browse files Browse the repository at this point in the history
Commit d5012a7 introduced a Python
2.7 dependency into python_stub_template.txt.  Unfortunately this stub
is non-hermetic, so even if the user has configured Python 2.7 and 3
`py_runtime`s, their builds may fail if the system-provided Python is ancient
(ex: CentOS 6.6 provides Python 2.6.6).

Accommodate ancient Python by reworking the path deduplication in terms
of a `set` and a generator instead of `collections.OrderedDict`.

Workaround for #11265.

Testing Done:
- `bazelisk test //src/test/shell/integration:python_stub_test`
- In a CentOS 6.6 env:
```console
$ /usr/bin/env python -V
Python 2.6.6
$ cat >test.py <<EOF
import sys
print(sys.executable)
EOF
$ cat >BUILD <<EOF
py_binary(name = "test", srcs = ["test.py"])
EOF
$ bazel run :test
/path/to/my/hermetic/python3
```

Closes #11269.

PiperOrigin-RevId: 309450777
  • Loading branch information
rbeasley authored and copybara-github committed May 1, 2020
1 parent 3862f87 commit d95bfbd
Showing 1 changed file with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
#!/usr/bin/env python

# This script must retain compatibility with a wide variety of Python versions
# since it is run for every py_binary target. Currently we guarantee support
# going back to Python 2.7, and try to support even Python 2.6 on a best-effort
# basis. We might abandon 2.6 support once users have the ability to control the
# above shebang string via the Python toolchain (#8685).

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
Expand All @@ -18,7 +24,6 @@ import shutil
import subprocess
import tempfile
import zipfile
import collections

# Return True if running on Windows
def IsWindows():
Expand Down Expand Up @@ -264,7 +269,11 @@ https://github.com/bazelbuild/bazel/issues/7899 for more information.

def Deduplicate(items):
"""Efficiently filter out duplicates, keeping the first element only."""
return list(collections.OrderedDict((it, None) for it in items).keys())
seen = set()
for it in items:
if it not in seen:
seen.add(it)
yield it

def Main():
args = sys.argv[1:]
Expand All @@ -281,8 +290,10 @@ def Main():
python_path_entries += GetRepositoriesImports(module_space, %import_all%)
# Remove duplicates to avoid overly long PYTHONPATH (#10977). Preserve order,
# keep first occurrence only.
python_path_entries = Deduplicate(python_path_entries)
python_path_entries = [GetWindowsPathWithUNCPrefix(d) for d in python_path_entries]
python_path_entries = [
GetWindowsPathWithUNCPrefix(d)
for d in Deduplicate(python_path_entries)
]

old_python_path = os.environ.get('PYTHONPATH')
python_path = os.pathsep.join(python_path_entries)
Expand Down

0 comments on commit d95bfbd

Please sign in to comment.