diff --git a/news/windows-long-paths.fixed.md b/news/windows-long-paths.fixed.md new file mode 100644 index 0000000000..960e328d09 --- /dev/null +++ b/news/windows-long-paths.fixed.md @@ -0,0 +1,5 @@ +(binaries/tests) (Windows) {obj}`py_binary` and {obj}`py_test` work with +runfiles paths of 260 characters or more when `LongPathsEnabled` is off, which +is the default. Before, the venv created at runtime without the privilege to +create symlinks could be missing files, and the runfiles directory wasn't found, +so imports failed. diff --git a/python/private/python_bootstrap_template.txt b/python/private/python_bootstrap_template.txt index 72bf62ddad..9ff22cae44 100644 --- a/python/private/python_bootstrap_template.txt +++ b/python/private/python_bootstrap_template.txt @@ -129,6 +129,10 @@ _symlinks_supported = not ( # symlinks can't be created needs to clean up. _WINDOWS_FALLBACK_MIN_BUILD = 17763 +# Windows paths at least this long need the \\?\ prefix. It's 248 rather than +# 260 (MAX_PATH) because that's the limit for creating directories. +_MAX_PATH_WITHOUT_PREFIX = 248 + # Windows APIs can be picky about slashes depending on the context, # so convert to backslashes to avoid any issues. if IS_WINDOWS: @@ -152,10 +156,11 @@ if IS_WINDOWS: if PYTHON_BINARY_ACTUAL and not has_windows_executable_extension(PYTHON_BINARY_ACTUAL): PYTHON_BINARY_ACTUAL = PYTHON_BINARY_ACTUAL + ".exe" -def get_windows_path_with_unc_prefix(path): +def get_windows_path_with_unc_prefix(path, always=False): """Adds UNC prefix after getting a normalized absolute Windows path. - No-op for non-Windows platforms or if running under python2. + No-op for non-Windows platforms or if running under python2. Unless `always` + is set, the prefix is only added to paths that are too long without it. """ path = path.strip() @@ -164,33 +169,53 @@ def get_windows_path_with_unc_prefix(path): if not IS_WINDOWS or sys.version_info[0] < 3: return path - # Starting in Windows 10, version 1607(OS build 14393), MAX_PATH limitations have been - # removed from common Win32 file and directory functions. - # Related doc: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later - import platform - win32_version = None - # Windows 2022 with Python 3.12.8 gives flakey errors, so try a couple times. - for _ in range(3): - try: - win32_version = platform.win32_ver()[1] - break - except (ValueError, KeyError): - pass - if win32_version and win32_version >= '10.0.14393': - return path - # import sysconfig only now to maintain python 2.6 compatibility import sysconfig if sysconfig.get_platform() == 'mingw': return path - # Lets start the unicode fun unicode_prefix = '\\\\?\\' if path.startswith(unicode_prefix): return path # abspath returns a normalized absolute path - return unicode_prefix + abspath(path) + path = abspath(path) + # Only add the prefix when it's needed, so that other paths, e.g. __file__, + # are unchanged: the prefix turns off normalization, e.g. of "..". + if not always and len(path) < _MAX_PATH_WITHOUT_PREFIX: + return path + if _long_paths_enabled(): + return path + if path.startswith('\\\\'): + return unicode_prefix + 'UNC\\' + path[2:] + return unicode_prefix + path + +def strip_windows_unc_prefix(path): + """Removes the prefix that get_windows_path_with_unc_prefix() adds.""" + if path.startswith('\\\\?\\UNC\\'): + return '\\\\' + path[8:] + if path.startswith('\\\\?\\'): + return path[4:] + return path + +_long_paths_enabled_result = None + +def _long_paths_enabled(): + """Returns whether LongPathsEnabled is set, which is off by default.""" + global _long_paths_enabled_result + if _long_paths_enabled_result is None: + # Read the registry instead of calling RtlAreLongPathsEnabled() through + # ctypes. ctypes needs to load _ctypes.pyd, and LongPathsEnabled doesn't + # apply to loading DLLs, so the import fails when Python itself is under + # a long path, e.g. in runfiles. winreg is built in, so it always works. + # python.exe opts in to long paths, so the registry value is enough. + try: + import winreg + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem") as key: + _long_paths_enabled_result = bool(winreg.QueryValueEx(key, "LongPathsEnabled")[0]) + except (ImportError, OSError): + _long_paths_enabled_result = False + return _long_paths_enabled_result def search_path(name): """Finds a file in a given search path.""" @@ -268,7 +293,8 @@ def find_runfiles_root(main_rel_path): runfiles_dir = runfiles_manifest_file[:-9] # Be defensive: the runfiles dir should contain our main entry point. If # it doesn't, then it must not be our runfiles directory. - if runfiles_dir and os.path.exists(join(runfiles_dir, main_rel_path)): + if runfiles_dir and os.path.exists( + get_windows_path_with_unc_prefix(join(runfiles_dir, main_rel_path))): return runfiles_dir # Clear RUNFILES_DIR & RUNFILES_MANIFEST_FILE since the runfiles dir was @@ -356,19 +382,23 @@ def _symlink_tree(link_from, link_to): # Ensure the source is an absolute path to simplify symlinking link_to_root = abspath(link_to) link_from_root = abspath(link_from) + # Walk with the \\?\ prefix, or os.walk() skips directories with long + # paths, but only pass the prefix on for the paths that need it. + walk_root = get_windows_path_with_unc_prefix(link_to_root, always=True) # This is non-optimal because it recreates the entire # venv site-packages tree (as opposed to finding a highest-common # directory to symlink). But its easy and understandable. - for root, dirs, files in os.walk(link_to_root): - rel_path = os.path.relpath(root, link_to_root) - link_from_dir = join(link_from_root, rel_path) + for root, dirs, files in os.walk(walk_root): + rel_path = os.path.relpath(root, walk_root) + link_from_dir = get_windows_path_with_unc_prefix( + join(link_from_root, rel_path)) if not os.path.exists(link_from_dir): os.makedirs(link_from_dir) for name in files: - link_to = join(root, name) + link_to = join(link_to_root, rel_path, name) link_from = join(link_from_dir, name) _symlink_exist_ok(from_=link_from, to=link_to) @@ -416,6 +446,8 @@ print(site.getsitepackages(["{venv_src}"])[-1]) venv_lib = join(venv, LIB_DIR_NAME) runfiles_venv_lib = join(runfiles_venv, LIB_DIR_NAME) + runfiles_venv_lib = get_windows_path_with_unc_prefix(runfiles_venv_lib) + venv_bin = join(venv, BIN_DIR_NAME) try: os.mkdir(venv_bin) @@ -435,7 +467,8 @@ print(site.getsitepackages(["{venv_src}"])[-1]) target = join(python_home, f) _symlink_exist_ok(from_=venv_path, to=target) - runfiles_venv_bin = join(runfiles_venv, BIN_DIR_NAME) + runfiles_venv_bin = get_windows_path_with_unc_prefix( + join(runfiles_venv, BIN_DIR_NAME)) # The runfiles bin directory may not exist if it's empty, e.g. # supports_build_time_venv=False and the interpreter is resolved at # runtime. @@ -631,6 +664,8 @@ def _run_execv(python_program, argv, env): def _symlink_exist_ok(*, from_, to): """Creates a symlink, or on Windows, a hard link, junction or copy if that's not possible.""" global _symlinks_supported + from_ = get_windows_path_with_unc_prefix(from_) + to = get_windows_path_with_unc_prefix(to) # On Windows, symlinks have to be told whether they're # pointing to a file or directory. Python is supposed to auto-detect # this, but in practice, this doesn't reliably happen. @@ -679,7 +714,9 @@ def _link_dir_windows(from_, to): import _winapi try: # Junctions don't need any privileges, but need an absolute target. - _winapi.CreateJunction(to, from_) + # CreateJunction() adds its own prefix to the target, and the target + # doesn't have the MAX_PATH limit, so remove ours. + _winapi.CreateJunction(strip_windows_unc_prefix(to), from_) # Another process sharing RULES_PYTHON_EXTRACT_ROOT created it first. except FileExistsError: return diff --git a/python/private/site_init_template.py b/python/private/site_init_template.py index 1c37241b1c..368ebc14e5 100644 --- a/python/private/site_init_template.py +++ b/python/private/site_init_template.py @@ -60,35 +60,6 @@ def _print_verbose(*args, mapping=None, values=None): _print_verbose("interpreter_actual_path:", _INTERPRETER_ACTUAL_PATH) -def _find_runfiles_root(): - # Give preference to the environment variables - runfiles_dir = os.environ.get("RUNFILES_DIR", None) - if not runfiles_dir: - runfiles_manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE", "") - if runfiles_manifest_file.endswith( - ".runfiles_manifest" - ) or runfiles_manifest_file.endswith(".runfiles/MANIFEST"): - runfiles_dir = runfiles_manifest_file[:-9] - - # Be defensive: the runfiles dir should contain ourselves. If it doesn't, - # then it must not be our runfiles directory. - if runfiles_dir and os.path.exists( - os.path.join(runfiles_dir, _SELF_RUNFILES_RELATIVE_PATH) - ): - return runfiles_dir - - num_dirs_to_runfiles_root = _SELF_RUNFILES_RELATIVE_PATH.count("/") + 1 - runfiles_root = os.path.dirname(__file__) - for _ in range(num_dirs_to_runfiles_root): - runfiles_root = os.path.dirname(runfiles_root) - return runfiles_root - - -_RUNFILES_ROOT = _find_runfiles_root() - -_print_verbose("runfiles_root:", _RUNFILES_ROOT) - - def _is_windows(): return os.name == "nt" @@ -118,6 +89,39 @@ def _get_windows_path_with_unc_prefix(path): return extended_path_prefix + path +def _find_runfiles_root(): + # Give preference to the environment variables + runfiles_dir = os.environ.get("RUNFILES_DIR", None) + if not runfiles_dir: + runfiles_manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE", "") + if runfiles_manifest_file.endswith( + ".runfiles_manifest" + ) or runfiles_manifest_file.endswith(".runfiles/MANIFEST"): + runfiles_dir = runfiles_manifest_file[:-9] + + # Be defensive: the runfiles dir should contain ourselves. If it doesn't, + # then it must not be our runfiles directory. + # Without the \\?\ prefix, exists() is False for paths that are too long, + # unless LongPathsEnabled is set. + if runfiles_dir and os.path.exists( + _get_windows_path_with_unc_prefix( + os.path.join(runfiles_dir, _SELF_RUNFILES_RELATIVE_PATH) + ) + ): + return runfiles_dir + + num_dirs_to_runfiles_root = _SELF_RUNFILES_RELATIVE_PATH.count("/") + 1 + runfiles_root = os.path.dirname(__file__) + for _ in range(num_dirs_to_runfiles_root): + runfiles_root = os.path.dirname(runfiles_root) + return runfiles_root + + +_RUNFILES_ROOT = _find_runfiles_root() + +_print_verbose("runfiles_root:", _RUNFILES_ROOT) + + def _install_windows_extension_finder(): """Use extended-length paths when loading long Windows extension paths.""" if not _is_windows() or sys.version_info[0] < 3: diff --git a/python/private/stage2_bootstrap_template.py b/python/private/stage2_bootstrap_template.py index d6662a00c7..ae389f4058 100644 --- a/python/private/stage2_bootstrap_template.py +++ b/python/private/stage2_bootstrap_template.py @@ -147,34 +147,46 @@ def get_windows_path_with_unc_prefix(path): if not IS_WINDOWS or sys.version_info[0] < 3: return path - # Starting in Windows 10, version 1607(OS build 14393), MAX_PATH limitations have been - # removed from common Win32 file and directory functions. - # Related doc: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later - import platform - - win32_version = None - # Windows 2022 with Python 3.12.8 gives flakey errors, so try a couple times. - for _ in range(3): - try: - win32_version = platform.win32_ver()[1] - break - except (ValueError, KeyError): - pass - if win32_version and win32_version >= "10.0.14393": - return path - # import sysconfig only now to maintain python 2.6 compatibility import sysconfig if sysconfig.get_platform() == "mingw": return path - # Lets start the unicode fun - if path.startswith(unicode_prefix): # noqa: F821 + unicode_prefix = "\\\\?\\" + if path.startswith(unicode_prefix): return path # os.path.abspath returns a normalized absolute path - return unicode_prefix + os.path.abspath(path) # noqa: F821 + path = os.path.abspath(path) + # Only add the prefix when it's needed, so that other paths, e.g. __file__, + # are unchanged: the prefix turns off normalization, e.g. of "..". 248 is + # the limit for directories. + if len(path) < 248 or _long_paths_enabled(): + return path + if path.startswith("\\\\"): + return unicode_prefix + "UNC\\" + path[2:] + return unicode_prefix + path + + +@cache +def _long_paths_enabled(): + """Returns whether LongPathsEnabled is set, which is off by default.""" + # Read the registry instead of calling RtlAreLongPathsEnabled() through + # ctypes. ctypes needs to load _ctypes.pyd, and LongPathsEnabled doesn't + # apply to loading DLLs, so the import fails when Python itself is under + # a long path, e.g. in runfiles. winreg is built in, so it always works. + # python.exe opts in to long paths, so the registry value is enough. + try: + import winreg + + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SYSTEM\CurrentControlSet\Control\FileSystem", + ) as key: + return bool(winreg.QueryValueEx(key, "LongPathsEnabled")[0]) + except (ImportError, OSError): + return False def print_verbose(*args, mapping=None, values=None): @@ -229,7 +241,9 @@ def find_runfiles_root(main_rel_path): runfiles_dir = runfiles_manifest_file[:-9] # Be defensive: the runfiles dir should contain our main entry point. If # it doesn't, then it must not be our runfiles directory. - if runfiles_dir and os.path.exists(os.path.join(runfiles_dir, main_rel_path)): + if runfiles_dir and os.path.exists( + get_windows_path_with_unc_prefix(os.path.join(runfiles_dir, main_rel_path)) + ): return runfiles_dir # Clear RUNFILES_DIR & RUNFILES_MANIFEST_FILE since the runfiles dir was diff --git a/python/private/zipapp/zip_main_template.py b/python/private/zipapp/zip_main_template.py index 7c965fc1f5..b0bca55c3f 100644 --- a/python/private/zipapp/zip_main_template.py +++ b/python/private/zipapp/zip_main_template.py @@ -104,27 +104,53 @@ def get_windows_path_with_unc_prefix(path): if not IS_WINDOWS or sys.version_info[0] < 3: return path - # Starting in Windows 10, version 1607(OS build 14393), MAX_PATH limitations have been - # removed from common Win32 file and directory functions. - # Related doc: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later - import platform - - if platform.win32_ver()[1] >= "10.0.14393": - return path - # import sysconfig only now to maintain python 2.6 compatibility import sysconfig if sysconfig.get_platform() == "mingw": return path - # Lets start the unicode fun unicode_prefix = "\\\\?\\" if path.startswith(unicode_prefix): return path # os.path.abspath returns a normalized absolute path - return unicode_prefix + os.path.abspath(path) + path = os.path.abspath(path) + # Only add the prefix when it's needed, so that other paths, e.g. __file__, + # are unchanged: the prefix turns off normalization, e.g. of "..". 248 is + # the limit for directories. + if len(path) < 248 or _long_paths_enabled(): + return path + if path.startswith("\\\\"): + return unicode_prefix + "UNC\\" + path[2:] + return unicode_prefix + path + + +_long_paths_enabled_result = None + + +def _long_paths_enabled(): + """Returns whether LongPathsEnabled is set, which is off by default.""" + global _long_paths_enabled_result + if _long_paths_enabled_result is None: + # Read the registry instead of calling RtlAreLongPathsEnabled() through + # ctypes. ctypes needs to load _ctypes.pyd, and LongPathsEnabled doesn't + # apply to loading DLLs, so the import fails when Python itself is under + # a long path, e.g. in runfiles. winreg is built in, so it always works. + # python.exe opts in to long paths, so the registry value is enough. + try: + import winreg + + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SYSTEM\CurrentControlSet\Control\FileSystem", + ) as key: + _long_paths_enabled_result = bool( + winreg.QueryValueEx(key, "LongPathsEnabled")[0] + ) + except (ImportError, OSError): + _long_paths_enabled_result = False + return _long_paths_enabled_result def search_path(name): diff --git a/tests/bootstrap_impls/BUILD.bazel b/tests/bootstrap_impls/BUILD.bazel index f2cd3a14c4..4dc5acbead 100644 --- a/tests/bootstrap_impls/BUILD.bazel +++ b/tests/bootstrap_impls/BUILD.bazel @@ -13,6 +13,7 @@ # limitations under the License. load("@rules_pkg//pkg:tar.bzl", "pkg_tar") load("@rules_shell//shell:sh_test.bzl", "sh_test") +load("//python:py_library.bzl", "py_library") load("//python:py_test.bzl", "py_test") load("//python:pytest_test.bzl", "pytest_test") load("//tests/support:py_reconfig.bzl", "py_reconfig_binary", "py_reconfig_test") @@ -149,12 +150,30 @@ pytest_test( ], ) +py_library( + name = "bootstrap_template_loader", + srcs = ["bootstrap_template_loader.py"], + data = [ + "//python/private:python_bootstrap_template.txt", + "//python/private:site_init_template", + "//python/private:stage2_bootstrap_template", + "//python/private/zipapp:zip_main_template", + ], + deps = ["//python/runfiles"], +) + py_test( name = "cached_venv_replaces_dangling_package_symlink_test", srcs = ["cached_venv_dangling_symlink_test.py"], - data = ["//python/private:python_bootstrap_template.txt"], main = "cached_venv_dangling_symlink_test.py", - deps = ["//python/runfiles"], + deps = [":bootstrap_template_loader"], +) + +py_test( + name = "windows_long_paths_test", + srcs = ["windows_long_paths_test.py"], + target_compatible_with = ["@platforms//os:windows"], + deps = [":bootstrap_template_loader"], ) py_reconfig_test( diff --git a/tests/bootstrap_impls/bootstrap_template_loader.py b/tests/bootstrap_impls/bootstrap_template_loader.py new file mode 100644 index 0000000000..04d3b567a6 --- /dev/null +++ b/tests/bootstrap_impls/bootstrap_template_loader.py @@ -0,0 +1,68 @@ +"""Loads the bootstrap templates as modules, for testing their functions.""" + +from __future__ import annotations + +import ast +import functools +import os +import pathlib +import sys + +from python.runfiles import runfiles + + +def _template_path(rel_path: str) -> pathlib.Path: + r = runfiles.Create() + if r: + path = r.Rlocation("rules_python/" + rel_path) + assert path is not None + return pathlib.Path(path) + return pathlib.Path(__file__).resolve().parents[2] / rel_path + + +def load_bootstrap() -> dict: + template = _template_path("python/private/python_bootstrap_template.txt") + source = template.read_text(encoding="utf-8") + for placeholder, value in [ + ("%shebang%", "#!/usr/bin/env python3"), + ("%stage2_bootstrap%", "unused.py"), + ("%runtime_venv_symlinks%", ""), + ]: + source = source.replace(placeholder, value) + + bootstrap = {"__name__": "bootstrap_test"} + saved_path = sys.path[:] + try: + exec(compile(source, str(template), "exec"), bootstrap) + finally: + sys.path[:] = saved_path + return bootstrap + + +def load_functions(rel_path: str, names: list[str]) -> dict: + """Loads some functions of a template without running the rest of it. + + Returns: + The globals of the functions, so that tests can replace the + functions that they call. + """ + template = _template_path(rel_path) + tree = ast.parse(template.read_text(encoding="utf-8")) + functions: list[ast.stmt] = [ + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name in names + ] + assert len(functions) == len(names), f"not all of {names} are in {rel_path}" + module = { + "__name__": "template_test", + "cache": functools.cache, + "os": os, + "sys": sys, + "IS_WINDOWS": os.name == "nt", + } + exec( + compile(ast.Module(body=functions, type_ignores=[]), str(template), "exec"), + module, + ) + return module diff --git a/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py b/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py index 35f9c54bad..2b2c4e6ccd 100644 --- a/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py +++ b/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py @@ -4,41 +4,10 @@ import os import pathlib -import sys import tempfile import unittest -from python.runfiles import runfiles - - -def _load_bootstrap() -> dict: - r = runfiles.Create() - if r: - template_path = r.Rlocation( - "rules_python/python/private/python_bootstrap_template.txt" - ) - assert template_path is not None - template = pathlib.Path(template_path) - else: - template = ( - pathlib.Path(__file__).resolve().parents[2] - / "python/private/python_bootstrap_template.txt" - ) - source = template.read_text(encoding="utf-8") - for placeholder, value in [ - ("%shebang%", "#!/usr/bin/env python3"), - ("%stage2_bootstrap%", "unused.py"), - ("%runtime_venv_symlinks%", ""), - ]: - source = source.replace(placeholder, value) - - bootstrap = {"__name__": "bootstrap_test"} - saved_path = sys.path[:] - try: - exec(compile(source, str(template), "exec"), bootstrap) - finally: - sys.path[:] = saved_path - return bootstrap +from tests.bootstrap_impls.bootstrap_template_loader import load_bootstrap def _can_create_symlinks() -> bool: @@ -82,7 +51,7 @@ def test_dangling_junction_is_detected_and_removed(self) -> None: self.assertFalse(os.path.lexists(junction)) def _test_replaces_dangling_package_link(self, *, symlinks_supported) -> None: - bootstrap = _load_bootstrap() + bootstrap = load_bootstrap() # False uses the fallback for when symlinks can't be created, which # creates a junction for a directory. bootstrap["_symlinks_supported"] = symlinks_supported diff --git a/tests/bootstrap_impls/windows_long_paths_test.py b/tests/bootstrap_impls/windows_long_paths_test.py new file mode 100644 index 0000000000..8003fe558c --- /dev/null +++ b/tests/bootstrap_impls/windows_long_paths_test.py @@ -0,0 +1,125 @@ +"""Tests the bootstrap with Windows paths that need the \\?\\ prefix.""" + +from __future__ import annotations + +import os +import shutil +import tempfile +import unittest +from unittest import mock + +from tests.bootstrap_impls.bootstrap_template_loader import ( + load_bootstrap, + load_functions, +) + +_PREFIX = "\\\\?\\" +# Over 260 characters, the limit without the prefix or LongPathsEnabled. +_LONG_REL_PATH = os.path.join(*["d" * 50] * 6) +_HELPER = "get_windows_path_with_unc_prefix" + + +@unittest.skipUnless(os.name == "nt", "Windows only") +class PrefixHelperTest(unittest.TestCase): + def _copies(self) -> dict: + """Returns the globals of each copy of the helper.""" + names = [_HELPER, "_long_paths_enabled"] + return { + "stage 1": load_bootstrap(), + "stage 2": load_functions( + "python/private/stage2_bootstrap_template.py", names + ), + "zipapp": load_functions( + "python/private/zipapp/zip_main_template.py", names + ), + } + + def test_prefix_is_only_added_when_needed(self) -> None: + long_path = "C:\\" + "a" * 300 + unc_path = "\\\\server\\share\\" + "a" * 300 + for name, module in self._copies().items(): + add_prefix = module[_HELPER] + with self.subTest(name, long_paths_enabled=False): + module["_long_paths_enabled"] = lambda: False + self.assertEqual(add_prefix("C:\\short"), "C:\\short") + self.assertEqual(add_prefix(long_path), _PREFIX + long_path) + self.assertEqual(add_prefix(unc_path), _PREFIX + "UNC\\" + unc_path[2:]) + self.assertEqual(add_prefix(_PREFIX + "C:\\x"), _PREFIX + "C:\\x") + with self.subTest(name, long_paths_enabled=True): + module["_long_paths_enabled"] = lambda: True + self.assertEqual(add_prefix(long_path), long_path) + + def test_site_init_converts_unc_paths(self) -> None: + module = load_functions( + "python/private/site_init_template.py", + ["_is_windows", "_get_windows_path_with_unc_prefix"], + ) + add_prefix = module["_get_windows_path_with_unc_prefix"] + self.assertEqual(add_prefix("C:\\x"), _PREFIX + "C:\\x") + self.assertEqual( + add_prefix("\\\\server\\share\\x"), _PREFIX + "UNC\\server\\share\\x" + ) + + +@unittest.skipUnless(os.name == "nt", "Windows only") +class LinkFallbackTest(unittest.TestCase): + """Uses the real LongPathsEnabled setting, so it passes either way.""" + + def setUp(self) -> None: + self.bootstrap = load_bootstrap() + # Use the fallback for when symlinks can't be created. + self.bootstrap["_symlinks_supported"] = False + self.temp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, _PREFIX + self.temp) + + def _write_long_file(self, root: str) -> str: + path = os.path.join(root, _LONG_REL_PATH, "file.txt") + os.makedirs(_PREFIX + os.path.dirname(path)) + with open(_PREFIX + path, "w") as f: + f.write("hello") + return path + + def test_links_a_long_file(self) -> None: + target = self._write_long_file(self.temp) + link = os.path.join(self.temp, "link.txt") + + self.bootstrap["_symlink_exist_ok"](from_=link, to=target) + + with open(link) as f: + self.assertEqual(f.read(), "hello") + + def test_links_a_long_directory(self) -> None: + target = os.path.dirname(self._write_long_file(self.temp)) + link = os.path.join(self.temp, "link") + + self.bootstrap["_symlink_exist_ok"](from_=link, to=target) + + self.assertEqual(os.listdir(link), ["file.txt"]) + + def test_symlink_tree_includes_long_paths(self) -> None: + src = os.path.join(self.temp, "src") + self._write_long_file(src) + dest = os.path.join(self.temp, "dest") + + self.bootstrap["_symlink_tree"](link_from=dest, link_to=src) + + with open(_PREFIX + os.path.join(dest, _LONG_REL_PATH, "file.txt")) as f: + self.assertEqual(f.read(), "hello") + + def test_symlink_tree_keeps_short_targets_unprefixed(self) -> None: + self.bootstrap["_symlinks_supported"] = True + src = os.path.join(self.temp, "src") + os.makedirs(os.path.join(src, "pkg")) + target = os.path.join(src, "pkg", "mod.py") + open(target, "w").close() + + with mock.patch("os.symlink") as symlink: + self.bootstrap["_symlink_tree"]( + link_from=os.path.join(self.temp, "dest"), link_to=src + ) + + self.assertEqual(symlink.call_args.args[0], target) + + +if __name__ == "__main__": + unittest.main()