okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main (0.2.1.1 long-path hotfix)bb7e399c3

main
5.8 KiB118 linesraw
1"""Windows path length (MAX_PATH).
2
3A Windows PC with "long paths" off (the default on a fresh install) refuses any ordinary file path of 260 characters or more.
4The AMD engine packages hold paths up to 149 characters (hipBLASLt tensile libraries), so under a long user name the unpacked
5engine can go past the limit. Two defences, neither of which needs a setting from the user:
6
7* every file Strata itself touches inside a component folder goes through `long_path`, which turns the path into the
8  extended-length form (``\\\\?\\C:\\...``) that Windows accepts at any length (up to 32,767 characters);
9* when a folder is still too deep for the engine's *own* file loading (the GPU math libraries open their files with ordinary
10  paths), `warning_for` gives one plain sentence with the fix; the install continues (recommend, never refuse).
11
12Nothing here reads or writes the registry. `plain_long_paths_work` finds out by trying.
13"""
14from __future__ import annotations
15
16import os
17import shutil
18import uuid
19from pathlib import Path
20
21#: the longest ordinary path Windows accepts with long paths off (MAX_PATH is 260 including the terminating null)
22PLAIN_LIMIT = 259
23_PREFIX = "\\\\?\\"
24_UNC_PREFIX = "\\\\?\\UNC\\"
25
26#: longest path inside an engine package, by backend, as shipped in 0.2.1 (hip: rocm/bin/hipblaslt/library/gfx1200/TensileLibrary_...).
27#: The warning before a download can only estimate; after unpacking the real manifest is measured.
28LONGEST_IN_PACKAGE = {"hip": 150}
29LONGEST_IN_PACKAGE_DEFAULT = 60
30
31
32def long_path(path) -> Path:
33    """`path` in the form that works at any length: absolute, normalised, with the ``\\\\?\\`` prefix on Windows. Elsewhere unchanged."""
34    p = Path(path)
35    if os.name != "nt":
36        return p
37    text = str(p)
38    if text.startswith(_PREFIX):
39        return p
40    text = os.path.normpath(os.path.abspath(text))
41    if text.startswith("\\\\"):
42        return Path(_UNC_PREFIX + text[2:])
43    return Path(_PREFIX + text)
44
45
46def plain(path) -> str:
47    """The path as a person would read it, without the extended-length prefix."""
48    text = str(path)
49    if text.startswith(_UNC_PREFIX):
50        return "\\\\" + text[len(_UNC_PREFIX):]
51    return text[len(_PREFIX):] if text.startswith(_PREFIX) else text
52
53
54def same_tree(path: Path, root: Path) -> bool:
55    """Whether the (already resolved) `path` is `root` or below it; the prefix on either side does not matter."""
56    a, b = os.path.normcase(plain(path)), os.path.normcase(plain(root))
57    return a == b or a.startswith(b.rstrip("\\/") + os.sep)
58
59
60def too_long(path, *, extra: int = 0) -> bool:
61    """Would an ordinary (not extended) path be refused? Only ever true on Windows."""
62    if os.name != "nt":
63        return False
64    return len(os.path.abspath(plain(path))) + extra > PLAIN_LIMIT
65
66
67def plain_long_paths_work(directory: Path) -> bool:
68    """Whether this process can open a path longer than 259 characters without the extended prefix (so Windows long paths are on).
69    Tried, not read from the registry: a few folders are made through the extended form and reached through the ordinary one."""
70    if os.name != "nt":
71        return True
72    base = long_path(Path(directory) / f".lp-{uuid.uuid4().hex[:6]}")
73    try:
74        deep = base / ("a" * 90) / ("b" * 90) / ("c" * 90)
75        os.makedirs(deep)
76        try:
77            return os.path.isdir(plain(deep)) and len(plain(deep)) > PLAIN_LIMIT
78        except OSError:
79            return False
80    except OSError:
81        return True                                    # could not even test: say nothing rather than warn wrongly
82    finally:
83        shutil.rmtree(base, ignore_errors=True)
84
85
86def warning_for(folder: Path, longest_inside: int) -> str | None:
87    """One plain sentence when the files of a package placed in `folder` would pass the ordinary path limit, else None."""
88    if os.name != "nt" or not too_long(Path(folder) / ("x" * (longest_inside + 1))):
89        return None
90    reach = len(plain(folder)) + 1 + longest_inside
91    return (f"Strata's folder is deep: some engine files will have paths of about {reach} characters, and Windows stops at 259 unless "
92            f"long paths are turned on. The install carries on, but the engine's graphics libraries may fail to load those files. "
93            f"To fix it, turn on Windows long paths (Group Policy: Enable Win32 long paths) or put Strata in a shorter folder "
94            f"(for example set STRATA_COMPONENTS_DIR to C:\\Strata) and update again.")
95
96
97def describe_oserror(exc: BaseException) -> str:
98    """Plain words for a failed file operation: which file, and when the cause is a path that is too long, that."""
99    name = getattr(exc, "filename", None) or getattr(exc, "filename2", None)
100    kind = type(exc).__name__
101    if name is not None:
102        shown = plain(os.fsdecode(name))
103        if too_long(shown):
104            return (f"a file path is longer than Windows allows ({len(os.path.abspath(shown))} characters, the limit is {PLAIN_LIMIT}): "
105                    f"{shown}. Windows long paths are off on this PC. Put Strata in a shorter folder (set STRATA_COMPONENTS_DIR "
106                    f"to something short like C:\\Strata) or turn on Windows long paths, then try again ({kind})")
107        if isinstance(exc, FileNotFoundError):
108            return f"Strata could not find or create {shown} ({kind})"
109        if isinstance(exc, PermissionError):
110            return f"Windows or another program would not let Strata use {shown} ({kind})"
111        reason = getattr(exc, "strerror", None)
112        return f"Strata could not use {shown}" + (f": {reason}" if reason else "") + f" ({kind})"
113    return f"a file operation failed ({kind})"
114
115
116def file_words(exc: BaseException) -> str:
117    """The one-line message the command line prints for a failed local file operation."""
118    return "local file operation failed: " + describe_oserror(exc)