diff --git a/tests/test_awc_names.py b/tests/test_awc_names.py index ad816941dc..cb14505396 100644 --- a/tests/test_awc_names.py +++ b/tests/test_awc_names.py @@ -294,6 +294,86 @@ def test_hashdict_json_words(self): path = write(os.path.join(tmp, "hashes.json"), json.dumps({"0000abcd": "Some_Word"})) self.assertEqual(A.read_words(path), ["Some_Word"]) + def named_rows(self, tmp, words): + """Run the CLI on a bank holding two dialogue streams with ``words`` as --words; the CSV rows it names.""" + banks = os.path.join(tmp, "banks") + os.mkdir(banks) + write(os.path.join(banks, "dlg.awc"), make_bank(["zz_rootau_abcd_01", "zz_rootau_efgh_01"])) + out = os.path.join(tmp, "names.csv") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(A.main([banks, "--words", words, "--out", out]), 0) + with open(out, encoding="utf-8", newline="") as fh: + return list(csv.DictReader(fh)) + + def test_word_list_with_utf8_bom_keeps_its_first_word(self): + # Windows PowerShell 5.1's `Out-File -Encoding utf8` starts the file with a BOM; read as plain UTF-8 it stuck + # to the first word ("zz_rootau_abcd_01"), which then named nothing. + lines = "zz_rootau_abcd_01\r\nzz_rootau_efgh_01\r\n" + with tempfile.TemporaryDirectory() as tmp: + plain = self.named_rows(tmp, write(os.path.join(tmp, "plain.txt"), lines.encode("utf-8"))) + with tempfile.TemporaryDirectory() as tmp: + bom = self.named_rows(tmp, write(os.path.join(tmp, "bom.txt"), b"\xef\xbb\xbf" + lines.encode("utf-8"))) + self.assertEqual(A.read_words(os.path.join(tmp, "bom.txt")), ["zz_rootau_abcd_01", "zz_rootau_efgh_01"]) + self.assertEqual(len(plain), 2) + self.assertEqual(len(bom), len(plain)) + + def test_hashdict_json_words_with_utf8_bom(self): + with tempfile.TemporaryDirectory() as tmp: + path = write(os.path.join(tmp, "hashes.json"), b"\xef\xbb\xbf" + b'{"0000abcd": "Some_Word"}') + self.assertEqual(A.read_words(path), ["Some_Word"]) + + def test_utf16_word_list_reports_rc_2_instead_of_naming_nothing(self): + # Windows PowerShell 5.1's `>` writes UTF-16LE with a BOM; read as UTF-8 no word matched and the run exited 0. + for bom, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")): + with self.subTest(codec=codec), tempfile.TemporaryDirectory() as tmp: + write(os.path.join(tmp, "dlg.awc"), make_bank(["zz_rootau_abcd_01"])) + words = write(os.path.join(tmp, "words.txt"), bom + "zz_rootau_abcd_01\r\n".encode(codec)) + err = io.StringIO() + with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): + rc = A.main([tmp, "--words", words, "--out", os.path.join(tmp, "o.csv")]) + self.assertEqual(rc, 2) + self.assertIn("UTF-16", err.getvalue()) + self.assertNotIn("Traceback", err.getvalue()) + + def test_utf16_word_list_without_bom_reports_rc_2(self): + # UTF-16 written without a BOM has no marker to sniff; its NUL bytes give it away, as no word holds one. + for codec in ("utf-16-le", "utf-16-be"): + with self.subTest(codec=codec), tempfile.TemporaryDirectory() as tmp: + write(os.path.join(tmp, "dlg.awc"), make_bank(["zz_rootau_abcd_01"])) + words = write(os.path.join(tmp, "words.txt"), "zz_rootau_abcd_01\r\n".encode(codec)) + err = io.StringIO() + with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): + rc = A.main([tmp, "--words", words, "--out", os.path.join(tmp, "o.csv")]) + self.assertEqual(rc, 2) + self.assertIn("UTF-16", err.getvalue()) + self.assertNotIn("Traceback", err.getvalue()) + + def test_nul_past_the_first_64_bytes_is_still_refused(self): + # BOM-less UTF-16 whose first characters have no zero byte (e.g. a long Cyrillic line) shows NULs only later. + with tempfile.TemporaryDirectory() as tmp: + words = write(os.path.join(tmp, "words.txt"), ("ж" * 40 + "\r\nzz_word\r\n").encode("utf-16-le")) + with open(words, "rb") as fh: + self.assertNotIn(b"\x00", fh.read(64)) + with self.assertRaisesRegex(ValueError, "UTF-16"): + A.read_words(words) + + def test_brace_after_leading_space_is_a_text_word_list(self): + # Only a file whose first byte (after a BOM) is "{" is sniffed as hashdict.py JSON, as before the BOM fix. + with tempfile.TemporaryDirectory() as tmp: + words = write(os.path.join(tmp, "words.txt"), b" {not_json\nzz_word\n") + self.assertEqual(A.read_words(words), ["{not_json", "zz_word"]) + + def test_json_after_a_leading_newline_without_json_suffix_is_read_as_text(self): + # Pins main's rule: hashdict.py never writes leading whitespace, so such a file is a text list, not JSON. + with tempfile.TemporaryDirectory() as tmp: + words = write(os.path.join(tmp, "hashes"), b'\n{"0000abcd": "W"}') + self.assertEqual(A.read_words(words), ['{"0000abcd": "W"}']) + + def test_hashdict_json_with_utf8_bom_and_no_suffix(self): + with tempfile.TemporaryDirectory() as tmp: + bom_json = write(os.path.join(tmp, "hashes"), b"\xef\xbb\xbf" + b'{"0000abcd": "W"}') + self.assertEqual(A.read_words(bom_json), ["W"]) + def test_needs_a_dictionary(self): with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): A.main([ROOT]) diff --git a/tests/test_psin_names.py b/tests/test_psin_names.py index d7b2ddcd58..1c293de67b 100644 --- a/tests/test_psin_names.py +++ b/tests/test_psin_names.py @@ -78,6 +78,44 @@ def test_names_from_rpf9_names_json_and_text(self): f.write("prop_lamp_03\n\n") self.assertEqual(N.load_names([j, t]), {"prop_crate_01", "veh_frame", "prop_lamp_03"}) + def test_utf8_bom_is_not_part_of_the_first_name(self): + # Windows PowerShell 5.1's `Out-File -Encoding utf8` writes a BOM; it used to stay on the first name. + with tempfile.TemporaryDirectory() as d: + t, j = os.path.join(d, "n.txt"), os.path.join(d, "n.json") + with open(t, "wb") as f: + f.write(b"\xef\xbb\xbfprop_lamp_03\r\nveh_frame\r\n") + with open(j, "wb") as f: + f.write(b"\xef\xbb\xbf" + json.dumps({"files": [{"names": ["prop_crate_01.#dr"]}]}).encode()) + self.assertEqual(N.load_names([t, j]), {"prop_lamp_03", "veh_frame", "prop_crate_01"}) + + def test_utf16_name_list_is_refused(self): + # Windows PowerShell 5.1's `>` writes UTF-16; read as UTF-8 none of its names matched, silently. + with tempfile.TemporaryDirectory() as d: + t = os.path.join(d, "n.txt") + with open(t, "wb") as f: + f.write(b"\xff\xfe" + "prop_lamp_03\r\n".encode("utf-16-le")) + with self.assertRaisesRegex(ValueError, "UTF-16"): + N.load_names([t]) + + def test_utf16_name_list_without_bom_is_refused(self): + # No BOM to sniff, but UTF-16 text holds NUL bytes, which no name list does. + for codec in ("utf-16-le", "utf-16-be"): + with self.subTest(codec=codec), tempfile.TemporaryDirectory() as d: + t = os.path.join(d, "n.txt") + with open(t, "wb") as f: + f.write("prop_lamp_03\r\n".encode(codec)) + with self.assertRaisesRegex(ValueError, "UTF-16"): + N.load_names([t]) + + def test_nul_past_the_first_64_bytes_is_still_refused(self): + # BOM-less UTF-16 whose first characters have no zero byte (e.g. a long Cyrillic line) shows NULs only later. + with tempfile.TemporaryDirectory() as d: + t = os.path.join(d, "n.txt") + with open(t, "wb") as f: + f.write(("ж" * 40 + "\r\nprop_lamp_03\r\n").encode("utf-16-le")) + with self.assertRaisesRegex(ValueError, "UTF-16"): + N.load_names([t]) + class TestScan(unittest.TestCase): def folder(self, d, blobs): diff --git a/tools/awc_names.py b/tools/awc_names.py index 78b449b35e..b5c50aafc6 100644 --- a/tools/awc_names.py +++ b/tools/awc_names.py @@ -155,14 +155,23 @@ def _files(path: str): def read_words(path: str) -> list: - """Words from a text file (one per line) or a hashdict.py JSON object.""" + """Words from a text file (one per line) or a hashdict.py JSON object. A UTF-8 BOM (Windows PowerShell 5.1's + `Out-File -Encoding utf8`) is dropped instead of becoming part of the first word; a UTF-16 file (PowerShell + 5.1's `>`, or UTF-16 without a BOM, which a NUL byte anywhere in the file gives away, as no word holds one) + raises ValueError, since read as UTF-8 none of its words would match and the run would look clean.""" with open(path, "rb") as fh: - head = fh.read(1).lstrip() - if path.lower().endswith(".json") or head == b"{": - with open(path, encoding="utf-8") as fh: + data = fh.read() + head = data[:64] + if head[:2] in (b"\xff\xfe", b"\xfe\xff") or b"\x00" in data: + raise ValueError("the word list looks like UTF-16 (e.g. PowerShell 5.1's `>`), not UTF-8 text; save it as " + "UTF-8, e.g. with `Out-File -Encoding utf8`") + if head.startswith(b"\xef\xbb\xbf"): + head = head[3:] + if path.lower().endswith(".json") or head[:1] == b"{": + with open(path, encoding="utf-8-sig") as fh: doc = json.load(fh) return [str(v) for v in (doc.values() if isinstance(doc, dict) else doc)] - with open(path, encoding="utf-8", errors="replace") as fh: + with open(path, encoding="utf-8-sig", errors="replace") as fh: return [line.strip() for line in fh if line.strip()] diff --git a/tools/psin_names.py b/tools/psin_names.py index 61bc236911..3b208aec3e 100644 --- a/tools/psin_names.py +++ b/tools/psin_names.py @@ -91,9 +91,12 @@ def load_names(paths): JSON, or not the shape rpf9_names.py writes, raises ValueError naming the file (--names is repeatable).""" names = set() for path in paths: + # A UTF-8 BOM (Windows PowerShell 5.1's `Out-File -Encoding utf8`) is dropped instead of becoming part of the + # first name; a UTF-16 text list (PowerShell 5.1's `>`, or one without a BOM, which a NUL byte gives away) is + # refused, since read as UTF-8 none of its names match. A UTF-16 .json is already refused as "not JSON" below. if path.endswith(".json"): try: - with open(path, encoding="utf-8") as f: + with open(path, encoding="utf-8-sig") as f: doc = json.load(f) except (ValueError, RecursionError) as e: # ValueError: not JSON, or not UTF-8 raise ValueError(f"{path}: not JSON: {e}") from None @@ -107,7 +110,12 @@ def load_names(paths): "strings") names.update(SUFFIX.sub("", n) for n in listed) else: - with open(path, encoding="utf-8", errors="replace") as f: + with open(path, "rb") as f: + data = f.read() # UTF-16 without a BOM shows as a NUL byte; a name list never holds one + if data[:2] in (b"\xff\xfe", b"\xfe\xff") or b"\x00" in data: + raise ValueError(f"{path}: the name list looks like UTF-16 (e.g. PowerShell 5.1's `>`), not UTF-8 " + "text; save it as UTF-8, e.g. with `Out-File -Encoding utf8`") + with open(path, encoding="utf-8-sig", errors="replace") as f: names.update(line.strip() for line in f) names.discard("") return names