tools/spirv_stubs.py: preflight stub targets and harden CLI parsing

This commit is contained in:
kirigayakazima
2026-11-26 20:28:02 +08:00
parent a73a57e133
commit fcedc33eb0
2 changed files with 50 additions and 1 deletions

View File

@ -285,5 +285,44 @@ class IndexEncodingTest(unittest.TestCase):
self.assertEqual(os.listdir(os.path.join(tmp, "stubs")), ["vs_0.spv"])
class CliAndDirectoryGuardTest(unittest.TestCase):
def test_unknown_flag_and_blank_dir_fail_with_error(self):
tool = os.path.join(ROOT, "tools", "spirv_stubs.py")
for bad, expected in (("-x", "unknown option"), ("--bogus", "unknown option"), ("", "empty spirv dir"), (" ", "empty spirv dir")):
with self.subTest(arg=bad):
p = subprocess.run([sys.executable, "-I", tool, bad], capture_output=True, text=True)
self.assertNotEqual(p.returncode, 0)
self.assertIn(expected, p.stderr)
self.assertNotIn("Traceback", p.stderr)
def test_recursion_error_in_index_is_one_error_not_a_traceback(self):
with tempfile.TemporaryDirectory() as tmp:
idx = os.path.join(tmp, "index.json")
with open(idx, "w", encoding="utf-8", newline="\n") as f:
f.write("{}")
with patch.object(spirv_stubs.json, "load", side_effect=RecursionError("too deep")):
with self.assertRaises(SystemExit) as cm:
spirv_stubs.main([tmp])
msg = str(cm.exception)
self.assertIn("cannot read", msg)
self.assertIn("too deep", msg)
def test_preexisting_target_directory_aborts_before_writing_other_stubs(self):
with tempfile.TemporaryDirectory() as tmp:
stubs_dir = os.path.join(tmp, "stubs")
os.makedirs(os.path.join(stubs_dir, "vs_0.spv"))
index = {"ps_a": {"stage": "ps", "inputs": [0]}, "vs_a": {"stage": "vs", "outputs": [0]}}
with self.assertRaises(IsADirectoryError):
spirv_stubs.generate_for_index(tmp, index)
self.assertEqual(os.listdir(stubs_dir), ["vs_0.spv"])
def test_stubs_path_as_regular_file_raises_not_a_directory(self):
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, "stubs"), "wb") as f:
f.write(b"not a dir")
with self.assertRaises(NotADirectoryError):
spirv_stubs.generate_for_index(tmp, {"ps_a": {"stage": "ps", "inputs": [0]}})
if __name__ == "__main__":
unittest.main()

View File

@ -254,6 +254,12 @@ def generate_for_index(spirv_dir, index):
if not needed:
return []
stubs_dir = os.path.join(spirv_dir, "stubs")
if os.path.exists(stubs_dir) and not os.path.isdir(stubs_dir):
raise NotADirectoryError(f"stubs output path is not a directory: {stubs_dir}")
for kind, locs in sorted(needed):
target = os.path.join(stubs_dir, stub_name(kind, locs))
if os.path.isdir(target):
raise IsADirectoryError(f"stub target is a directory: {target}")
os.makedirs(stubs_dir, exist_ok=True)
written = []
for kind, locs in sorted(needed):
@ -290,13 +296,17 @@ def main(argv=None):
if len(argv) != 1:
sys.exit(__doc__)
spirv_dir = argv[0]
if spirv_dir.startswith("-"):
sys.exit(f"unknown option: {spirv_dir}\n{__doc__}")
if not spirv_dir.strip():
sys.exit(f"empty spirv dir\n{__doc__}")
idx_path = os.path.join(spirv_dir, "index.json")
if not os.path.isfile(idx_path):
sys.exit(f"missing {idx_path}")
try:
with open(idx_path, encoding="utf-8-sig") as f:
index = json.load(f)
except (OSError, ValueError) as e:
except (OSError, ValueError, RecursionError) as e:
sys.exit(f"cannot read {idx_path}: {e}")
if not isinstance(index, dict):
sys.exit(f"cannot read {idx_path}: expected a JSON object of shader -> metadata entries")