okami.mom/strata

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

Niko1221Merge main (0.2.1.1 long-path hotfix)bb7e399c3

main
8.3 KiB174 linesraw
1"""Windows MAX_PATH (260) and the engine installer.
2
3A fresh Windows PC has long paths off. `strata launch` on an AMD PC failed with "local file operation failed
4(FileNotFoundError)" because the staging folder (components\\.updates\\staging\\<12 hex>\\engine\\<folder>) plus the longest file in
5the hip packages (149 characters) went past 259 under an ordinary user name. This pins the path arithmetic for the real 0.2.1
6package file lists (tests/terminal/data/windows_package_paths.json, made from the release tarballs) and the behaviour of the fix."""
7
8import io
9import json
10import os
11import tarfile
12import tempfile
13import unittest
14from pathlib import Path, PureWindowsPath
15from unittest import mock
16
17from strata_control import engine_component as ec, longpath, updater
18
19DATA = json.loads((Path(__file__).parent / "data" / "windows_package_paths.json").read_text(encoding="utf-8"))
20LIMIT = longpath.PLAIN_LIMIT
21USER = "u" * 20
22COMPONENTS = PureWindowsPath(rf"C:\Users\{USER}\AppData\Local\Strata\components")      # what components_dir() gives on Windows
23LEGACY_STAGE = COMPONENTS / ".updates" / "staging" / ("0123456789ab")                    # what 0.2.1 used
24NEW_STAGE = COMPONENTS / updater.STAGE_DIR / "0123"
25WINDOWS = os.name == "nt"
26
27
28def longest(entry) -> str:
29    return max(entry["longest"], key=len)
30
31
32class PathArithmetic(unittest.TestCase):
33    def test_the_old_staging_folder_was_past_the_limit(self):
34        """The reproduction: with the 0.2.1 layout the AMD packages do not fit under a 20-character user name."""
35        too_long = {}
36        for e in DATA["engines"]:
37            n = len(str(LEGACY_STAGE / "engine" / e["folder"] / longest(e)))
38            if n > LIMIT:
39                too_long[e["folder"]] = n
40        self.assertEqual(sorted(too_long), ["0.1.46-windows-x86_64-hip-rdna3", "0.1.46-windows-x86_64-hip-rx9070"], too_long)
41
42    def test_every_staged_path_fits_for_a_20_character_user_name(self):
43        for e in DATA["engines"]:
44            n = len(str(NEW_STAGE / "engine" / e["folder"] / longest(e)))
45            self.assertLessEqual(n, LIMIT, f"{e['folder']}: staged path is {n} characters")
46
47    def test_every_final_path_fits_for_a_20_character_user_name(self):
48        for e in DATA["engines"]:
49            n = len(str(COMPONENTS / "engine" / e["folder"] / longest(e)))
50            self.assertLessEqual(n, LIMIT, f"{e['folder']}: installed path is {n} characters")
51        for c in DATA["control"]:
52            for base in (COMPONENTS / "control" / c["version"], COMPONENTS / updater.STAGE_DIR / "c0123"):
53                n = len(str(base / longest(c)))
54                self.assertLessEqual(n, LIMIT, f"control {c['version']}: path is {n} characters")
55
56    def test_staging_is_no_deeper_than_nine_characters_over_the_install(self):
57        live = COMPONENTS / "engine" / "x"
58        staged = NEW_STAGE / "engine" / "x"
59        self.assertLessEqual(len(str(staged)) - len(str(live)), 9)
60
61    def test_the_hip_estimate_covers_the_real_packages(self):
62        for e in DATA["engines"]:
63            if "-hip-" in e["folder"]:
64                self.assertGreaterEqual(longpath.LONGEST_IN_PACKAGE["hip"], len(longest(e)))
65
66
67class Messages(unittest.TestCase):
68    def test_a_missing_file_is_named(self):
69        words = longpath.file_words(FileNotFoundError(2, "No such file or directory", r"C:\x\y\z.dat"))
70        self.assertIn(r"C:\x\y\z.dat", words)
71        self.assertIn("FileNotFoundError", words)
72
73    def test_something_without_a_name_still_says_what_kind(self):
74        self.assertIn("(OSError)", longpath.file_words(OSError("boom")))
75
76    @unittest.skipUnless(WINDOWS, "the limit is a Windows one")
77    def test_a_path_that_is_too_long_says_so(self):
78        name = "C:\\" + "\\".join(["d" * 60] * 5) + "\\file.dat"
79        words = longpath.file_words(FileNotFoundError(2, "No such file or directory", name))
80        self.assertIn("longer than Windows allows", words)
81        self.assertIn("STRATA_COMPONENTS_DIR", words)
82        self.assertIn(name, words)
83
84    @unittest.skipUnless(WINDOWS, "the limit is a Windows one")
85    def test_no_warning_for_a_short_folder_and_one_for_a_deep_one(self):
86        self.assertIsNone(longpath.warning_for(Path(r"C:\Strata\engine\0.1.46-windows-x86_64-hip-rdna3"), 150))
87        deep = Path("C:/Users/" + USER + "/AppData/Local/Strata/components/engine/0.1.46-windows-x86_64-hip-rx9070/" + "q" * 30)
88        words = longpath.warning_for(deep, 150)
89        self.assertIn("long paths", words)
90        self.assertIn("carries on", words)
91
92
93@unittest.skipUnless(WINDOWS, "extended-length paths are a Windows thing")
94class DeepFolders(unittest.TestCase):
95    def setUp(self):
96        self.temp = tempfile.TemporaryDirectory(prefix="strata-lp-")
97        self.addCleanup(lambda: __import__("shutil").rmtree(longpath.long_path(self.temp.name), ignore_errors=True))
98        self.deep = Path(self.temp.name) / ("p" * 120) / ("q" * 120)
99
100    def archive(self, member, data=b"engine bytes"):
101        raw = io.BytesIO()
102        with tarfile.open(fileobj=raw, mode="w:gz") as tar:
103            info = tarfile.TarInfo(member)
104            info.size = len(data)
105            tar.addfile(info, io.BytesIO(data))
106        path = Path(self.temp.name) / "pkg.tar.gz"
107        path.write_bytes(raw.getvalue())
108        return path
109
110    def test_long_path_adds_the_prefix_once(self):
111        p = longpath.long_path(r"C:\a\b")
112        self.assertTrue(str(p).startswith("\\\\?\\C:\\a"))
113        self.assertEqual(longpath.long_path(p), p)
114        self.assertEqual(longpath.plain(p), r"C:\a\b")
115
116    def test_extract_goes_through_the_extended_form(self):
117        member = "rocm/bin/hipblaslt/library/gfx1151/" + "T" * 137 + ".dat.zlib"
118        archive = self.archive(member)
119        seen = []
120        real = updater.components.safe_extract
121
122        def spy(archive_, destination, **kw):
123            seen.append(str(destination))
124            return real(archive_, destination, **kw)
125
126        with mock.patch.object(updater.components, "safe_extract", spy):
127            updater.extract(archive, self.deep / "engine" / "x", "tar.gz", 1 << 20)
128        self.assertTrue(seen[0].startswith("\\\\?\\"), seen)
129        target = longpath.long_path(self.deep / "engine" / "x") / member
130        self.assertGreater(len(longpath.plain(target)), LIMIT)
131        self.assertEqual(target.read_bytes(), b"engine bytes")
132
133    def test_a_failed_unpack_names_the_file(self):
134        archive = self.archive("a/b.dat")
135        with mock.patch.object(updater.components, "safe_extract", side_effect=FileNotFoundError(3, "The system cannot find the path", r"C:\n\o.dat")):
136            with self.assertRaises(updater.UpdateError) as cm:
137                updater.extract(archive, self.deep, "tar.gz", 1 << 20)
138        self.assertIn(r"C:\n\o.dat", str(cm.exception))
139        self.assertEqual(cm.exception.exit_code, 6)
140
141    def test_verify_reads_files_that_sit_past_the_limit(self):
142        from tests.terminal import update_fixture as fx
143        root = Path(self.temp.name)
144        built = fx.build_package(root / "b", "0.1.45")
145        # a folder deep enough that the stub's files are past 259 characters
146        base = longpath.long_path(root / ("m" * 110) / ("n" * 110))
147        import shutil
148        shutil.copytree(longpath.long_path(built), base / built.name)
149        component = ec.read_manifest(base / built.name)
150        self.assertGreater(len(longpath.plain(base / built.name / component.entrypoint)), 0)
151        ec.verify(component, full=True)                                  # raises IntegrityProblem if a file looks missing
152
153    def test_the_probe_runs_and_cleans_up(self):
154        longpath.plain_long_paths_work(Path(self.temp.name))
155        self.assertEqual([p.name for p in Path(self.temp.name).iterdir() if p.name.startswith(".lp-")], [])
156
157
158class StagingFolder(unittest.TestCase):
159    def test_new_stage_is_short_and_sweeps_old_staging(self):
160        with tempfile.TemporaryDirectory(prefix="strata-stage-") as tmp:
161            root = Path(tmp)
162            old = root / ".updates" / "staging" / "abc"
163            old.mkdir(parents=True)
164            stale = root / updater.STAGE_DIR / "dead"
165            stale.mkdir(parents=True)
166            stage = updater.new_stage(root)
167            self.assertEqual(stage.parent, root / updater.STAGE_DIR)
168            self.assertEqual(len(stage.name), 4)
169            self.assertFalse(old.exists() or stale.exists())
170            self.assertTrue(updater.new_stage(root, "c").name.startswith("c"))
171
172
173if __name__ == "__main__":
174    unittest.main()