py2to3: migrate python_stub_template.txt

Add __future__ imports to ensure the stub works
with both PY2 and PY3. These are the only
PY3-related changes here.

The rest is all cosmetic changes to fix linter
errors: unified quoting style, added docstrings.
PiperOrigin-RevId: 279098205
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
index 052814d..a9705d4b 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 
+from __future__ import absolute_import
+from __future__ import division
 from __future__ import print_function
 
 import sys
@@ -12,10 +14,9 @@
 
 import os
 import re
-import tempfile
 import shutil
-import sys
 import subprocess
+import tempfile
 import zipfile
 
 # Return True if running on Windows
@@ -23,9 +24,9 @@
   return os.name == 'nt'
 
 def GetWindowsPathWithUNCPrefix(path):
-  """
-  Adding UNC prefix after getting a normalized absolute Windows path,
-  it's no-op for non-Windows platforms or if running under python2.
+  """Adds UNC prefix after getting a normalized absolute Windows path.
+
+  No-op for non-Windows platforms or if running under python2.
   """
   path = path.strip()
 
@@ -35,7 +36,7 @@
     return path
 
   # Lets start the unicode fun
-  unicode_prefix = "\\\\?\\"
+  unicode_prefix = '\\\\?\\'
   if path.startswith(unicode_prefix):
     return path
 
@@ -49,21 +50,21 @@
 if IsWindows() and not HasWindowsExecutableExtension(PYTHON_BINARY):
   PYTHON_BINARY = PYTHON_BINARY + '.exe'
 
-# Find a file in a given search path.
 def SearchPath(name):
+  """Finds a file in a given search path."""
   search_path = os.getenv('PATH', os.defpath).split(os.pathsep)
   for directory in search_path:
-    if directory == '': continue
-    path = os.path.join(directory, name)
-    if os.path.isfile(path) and os.access(path, os.X_OK):
-      return path
+    if directory:
+      path = os.path.join(directory, name)
+      if os.path.isfile(path) and os.access(path, os.X_OK):
+        return path
   return None
 
 def IsRunningFromZip():
   return %is_zipfile%
 
-# Find the real Python binary if it's not a normal absolute path
 def FindPythonBinary(module_space):
+  """Finds the real Python binary if it's not a normal absolute path."""
   if PYTHON_BINARY.startswith('//'):
     # Case 1: Path is a label. Not supported yet.
     raise AssertionError(
@@ -80,11 +81,11 @@
     return SearchPath(PYTHON_BINARY)
 
 def CreatePythonPathEntries(python_imports, module_space):
-  parts = python_imports.split(':');
-  return [module_space] + ["%s/%s" % (module_space, path) for path in parts]
+  parts = python_imports.split(':')
+  return [module_space] + ['%s/%s' % (module_space, path) for path in parts]
 
-# Find the runfiles tree
 def FindModuleSpace():
+  """Finds the runfiles tree."""
   stub_filename = sys.argv[0]
   if not os.path.isabs(stub_filename):
     stub_filename = os.path.join(os.getcwd(), stub_filename)
@@ -138,19 +139,19 @@
 
 # Create the runfiles tree by extracting the zip file
 def CreateModuleSpace():
-  temp_dir = tempfile.mkdtemp("", "Bazel.runfiles_")
+  temp_dir = tempfile.mkdtemp('', 'Bazel.runfiles_')
   ExtractZip(os.path.dirname(__file__), temp_dir)
-  return os.path.join(temp_dir, "runfiles")
+  return os.path.join(temp_dir, 'runfiles')
 
 # Returns repository roots to add to the import path.
 def GetRepositoriesImports(module_space, import_all):
   if import_all:
     repo_dirs = [os.path.join(module_space, d) for d in os.listdir(module_space)]
     return [d for d in repo_dirs if os.path.isdir(d)]
-  return [os.path.join(module_space, "%workspace_name%")]
+  return [os.path.join(module_space, '%workspace_name%')]
 
-# Finds the runfiles manifest or the runfiles directory.
 def RunfilesEnvvar(module_space):
+  """Finds the runfiles manifest or the runfiles directory."""
   # If this binary is the data-dependency of another one, the other sets
   # RUNFILES_MANIFEST_FILE or RUNFILES_DIR for our sake.
   runfiles = os.environ.get('RUNFILES_MANIFEST_FILE', None)
@@ -185,7 +186,7 @@
 # TODO(#6443): Remove this once there's no longer a host configuration for
 # Python targets to appear in.
 def MaybeEmitHostVersionWarning(ret_code):
-  """Warn the user if a failure may be due to the host config's version.
+  """Warns the user if a failure may be due to the host config's version.
 
   This emits a message to stderr if
     1) ret_code is non-zero,
@@ -215,7 +216,7 @@
 
   host_version = %python_version_from_config%
   target_version = %python_version_from_attr%
-  opposite_of_host_version = "2" if host_version == "3" else "3"
+  opposite_of_host_version = '2' if host_version == '3' else '3'
 
   if %python_version_specified_explicitly%:
     # Mismatch with explicitly declared version.
@@ -226,7 +227,7 @@
 the host configuration (for the entire build) to instead use Python \
 {target_version} by setting --host_force_python=PY{target_version}.\
 """.format(
-    target="%target%",
+    target='%target%',
     ret_code=ret_code,
     target_version=target_version,
     host_version=host_version)
@@ -240,7 +241,7 @@
 --host_force_python=PY{opposite_of_host_version}, which affects the entire \
 build.\
 """.format(
-    target="%target%",
+    target='%target%',
     ret_code=ret_code,
     host_version=host_version,
     opposite_of_host_version=opposite_of_host_version)
@@ -282,7 +283,7 @@
     python_path += os.pathsep + old_python_path
 
   if IsWindows():
-    python_path = python_path.replace("/", os.sep)
+    python_path = python_path.replace('/', os.sep)
 
   new_env['PYTHONPATH'] = python_path
   runfiles_envkey, runfiles_envvalue = RunfilesEnvvar(module_space)
@@ -294,7 +295,7 @@
   # main file of the Python binary in BazelPythonSemantics.java.
   rel_path = '%main%'
   if IsWindows():
-    rel_path = rel_path.replace("/", os.sep)
+    rel_path = rel_path.replace('/', os.sep)
 
   main_filename = os.path.join(module_space, rel_path)
   main_filename = GetWindowsPathWithUNCPrefix(main_filename)
@@ -316,8 +317,8 @@
       # If RUN_UNDER_RUNFILES equals 1, it means we need to
       # change directory to the right runfiles directory.
       # (So that the data files are accessible)
-      if os.environ.get("RUN_UNDER_RUNFILES") == "1":
-        os.chdir(os.path.join(module_space, "%workspace_name%"))
+      if os.environ.get('RUN_UNDER_RUNFILES') == '1':
+        os.chdir(os.path.join(module_space, '%workspace_name%'))
       ret_code = subprocess.call(args)
       shutil.rmtree(os.path.dirname(module_space), True)
       MaybeEmitHostVersionWarning(ret_code)