Skip to content

Commit 5fa8dce

Browse files
jimisolaclaude
andcommitted
fix: read sources and write annotations as UTF-8
open() without an encoding uses the platform locale, which is cp1252 on Windows, so any source file containing a UTF-8 byte undefined in cp1252 crashed the build hook with UnicodeDecodeError. Parse the raw bytes so ast decodes per PEP 263, and write annotations.yml explicitly as UTF-8. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mt2FAVc4k9yNuEdkfxHdQX Signed-off-by: Jimisola Laursen <jimisola@jimisola.com>
1 parent a1cc8a0 commit 5fa8dce

2 files changed

Lines changed: 69 additions & 3 deletions

File tree

‎src/reqstool_python_decorators/processors/decorator_processor.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from enum import Enum, unique
44
import os
5+
from pathlib import Path
56
from typing import ReadOnly, TypedDict
67
from ruamel.yaml import YAML
78
import ast
@@ -115,8 +116,9 @@ def get_functions_and_classes(self, file_path: str | os.PathLike, decorator_name
115116
- `name` (str): The name of the function or class.
116117
- `decorators` (list): List of dictionaries with decorator info including name and arguments e.g. "REQ_001".
117118
"""
118-
with open(file_path, "r") as file:
119-
tree = ast.parse(file.read(), filename=str(file_path))
119+
# Hand ast.parse the raw bytes so it decodes per PEP 263 (UTF-8 unless the file declares otherwise),
120+
# instead of the platform locale encoding (cp1252 on Windows), which rejects valid UTF-8 sources.
121+
tree = ast.parse(Path(file_path).read_bytes(), filename=str(file_path))
120122

121123
for node in ast.walk(tree):
122124
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
@@ -157,7 +159,7 @@ def write_to_yaml(self, output_file: str | os.PathLike, formatted_data) -> None:
157159
instance.write_to_yaml("output_file.yml", data)
158160
```
159161
"""
160-
with open(output_file, "w") as yaml_file:
162+
with open(output_file, "w", encoding="utf-8") as yaml_file:
161163
yaml = YAML()
162164
yaml.default_flow_style = False
163165
yaml_file.write(self.yaml_language_server)

‎tests/unit/reqstool_decorators/processors/test_processors.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import os
2+
import subprocess
3+
import sys
4+
15
import pytest
26
from reqstool_python_decorators.decorators.decorators import SVCs
37
from reqstool_python_decorators.processors.decorator_processor import DecoratorProcessor
@@ -325,3 +329,63 @@ def test_process_decorated_data_no_state_accumulation(process_decorator_instance
325329
# Should have exactly 1 entry, not 2 due to state accumulation
326330
entries = data["requirement_annotations"]["implementations"]["REQ_001"]
327331
assert len(entries) == 1
332+
333+
334+
# ---------------------------------------------------------------------------
335+
# non-ASCII sources / platform locale encoding
336+
# ---------------------------------------------------------------------------
337+
338+
# "Đ" is C4 90 in UTF-8; 0x90 is undefined in cp1252, so a locale-decoded read fails on Windows,
339+
# and any non-ASCII byte fails under an ASCII locale on Linux and macOS.
340+
_NON_ASCII_SOURCE = '# Đ non-ASCII comment\n@Requirements("REQ_001")\ndef my_func():\n """Đ"""\n'
341+
342+
_RUN_PROCESSOR = (
343+
"import sys\n"
344+
"from reqstool_python_decorators.processors.decorator_processor import DecoratorProcessor\n"
345+
"DecoratorProcessor().process_decorated_data([sys.argv[1]], output_file=sys.argv[2])\n"
346+
)
347+
348+
349+
@SVCs("SVC_DECORATORS_002", "SVC_DECORATORS_003")
350+
def test_process_decorated_data_non_ascii_source_with_non_utf8_locale(tmp_path):
351+
src_dir = tmp_path / "src"
352+
src_dir.mkdir()
353+
(src_dir / "mod.py").write_bytes(_NON_ASCII_SOURCE.encode("utf-8"))
354+
output_file = tmp_path / "out" / "annotations.yml"
355+
356+
# Run in a child process with UTF-8 mode off and a legacy locale to mimic a default Windows setup.
357+
env = {
358+
**os.environ,
359+
"PYTHONUTF8": "0",
360+
"PYTHONCOERCECLOCALE": "0",
361+
"PYTHONIOENCODING": "utf-8",
362+
"LC_ALL": "C",
363+
"LANG": "C",
364+
}
365+
result = subprocess.run(
366+
[sys.executable, "-c", _RUN_PROCESSOR, str(src_dir), str(output_file)],
367+
capture_output=True,
368+
text=True,
369+
env=env,
370+
)
371+
372+
assert result.returncode == 0, result.stderr
373+
data = YAML().load(output_file.read_text(encoding="utf-8"))
374+
assert [
375+
e["fullyQualifiedName"].rsplit(".", 1)[-1]
376+
for e in data["requirement_annotations"]["implementations"]["REQ_001"]
377+
] == ["my_func"]
378+
379+
380+
@SVCs("SVC_DECORATORS_002")
381+
def test_get_functions_and_classes_honours_pep263_encoding_declaration(
382+
process_decorator_instance: DecoratorProcessor, tmp_path
383+
):
384+
src_file = tmp_path / "latin1_mod.py"
385+
src_file.write_bytes(
386+
'# -*- coding: latin-1 -*-\n# é\n@Requirements("REQ_001")\ndef my_func():\n pass\n'.encode("latin-1")
387+
)
388+
389+
process_decorator_instance.get_functions_and_classes(src_file, ["Requirements"])
390+
391+
assert [r["name"] for r in process_decorator_instance.req_svc_results] == ["my_func"]

0 commit comments

Comments
 (0)