From c707fdb9f202bfc4d69ad4f4fbac513e164fd76d Mon Sep 17 00:00:00 2001 From: Jimisola Laursen Date: Sun, 22 Nov 2026 04:12:59 +0000 Subject: [PATCH] fix: read and write standard streams and text files as UTF-8 Redirected stdio on Windows uses cp1252, so `reqstool validate > file` crashed with UnicodeEncodeError on the status symbols it prints, and `reqstool enrich` could not decode UTF-8 on stdin. Only `report` had a per-command workaround (#502). - Reconfigure stdin/stdout/stderr to UTF-8 once at the start of main() and drop the report-specific reconfigure. - Pass encoding="utf-8" to the remaining open()/read_text() calls on text files: LSP schema, definition and root discovery reads, the .reqstool-ai.yaml config, the bundled JSON schemas, and the LSP log file handler. A UTF-8 requirements.yml was silently skipped by LSP root discovery under a legacy default encoding. Signed-off-by: Jimisola Laursen Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Mt2FAXZTXnbKG2Ho6GYy1z --- src/reqstool/command.py | 19 ++- src/reqstool/common/reqstool_ai_config.py | 2 +- .../common/validators/syntax_validator.py | 2 +- src/reqstool/lsp/features/definition.py | 4 +- src/reqstool/lsp/root_discovery.py | 4 +- src/reqstool/lsp/server.py | 12 +- src/reqstool/lsp/yaml_schema.py | 2 +- tests/unit/reqstool/test_command.py | 78 +++++++++++ tests/unit/reqstool/test_default_encoding.py | 132 ++++++++++++++++++ 9 files changed, 240 insertions(+), 15 deletions(-) create mode 100644 tests/unit/reqstool/test_default_encoding.py diff --git a/src/reqstool/command.py b/src/reqstool/command.py index 6586f503..22360e98 100755 --- a/src/reqstool/command.py +++ b/src/reqstool/command.py @@ -498,10 +498,6 @@ def command_report(self, report_args: argparse.Namespace): format=format, ) - if output is sys.stdout and (sys.stdout.encoding or "").lower().replace("-", "") != "utf8": - # Redirected output on Windows defaults to cp1252, which cannot encode the report. - sys.stdout.reconfigure(encoding="utf-8") - output.write(result.result) @Requirements("EXPORT_0004", "EXPORT_0005") @@ -676,7 +672,22 @@ def print_help(self): self.__parser.print_help(sys.stderr) +def _use_utf8_standard_streams() -> None: + """Read and write the standard streams as UTF-8 whatever the platform default is. + + Redirected stdio on Windows uses the ANSI code page (cp1252), which cannot encode the status symbols and report + characters reqstool writes, nor decode arbitrary UTF-8 on stdin. Streams that cannot be reconfigured (for example + ones replaced by a test harness) are left alone. + """ + for stream in (sys.stdin, sys.stdout, sys.stderr): + if (getattr(stream, "encoding", None) or "").lower().replace("-", "") != "utf8": + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is not None: + reconfigure(encoding="utf-8") + + def main(): # noqa: C901 + _use_utf8_standard_streams() command = Command() args = command.get_arguments() diff --git a/src/reqstool/common/reqstool_ai_config.py b/src/reqstool/common/reqstool_ai_config.py index 8eb27938..a593836d 100644 --- a/src/reqstool/common/reqstool_ai_config.py +++ b/src/reqstool/common/reqstool_ai_config.py @@ -27,7 +27,7 @@ def resolve_system_path(config_path: Path) -> Path: Raises ValueError if `system` or `system.path` is missing or not a string. """ yaml = _YAML() - with open(config_path) as f: + with open(config_path, encoding="utf-8") as f: data = yaml.load(f) or {} system = data.get("system") diff --git a/src/reqstool/common/validators/syntax_validator.py b/src/reqstool/common/validators/syntax_validator.py index 0f852b07..1f07432c 100644 --- a/src/reqstool/common/validators/syntax_validator.py +++ b/src/reqstool/common/validators/syntax_validator.py @@ -22,7 +22,7 @@ class JsonSchemaItem: schema_version = schema_module.__name__.split(".")[-1] def __post_init__(self): - self.schema = json.loads(files(self.schema_module).joinpath(self.short_uri).read_text()) + self.schema = json.loads(files(self.schema_module).joinpath(self.short_uri).read_text(encoding="utf-8")) @unique diff --git a/src/reqstool/lsp/features/definition.py b/src/reqstool/lsp/features/definition.py index c6beb452..98643e2b 100644 --- a/src/reqstool/lsp/features/definition.py +++ b/src/reqstool/lsp/features/definition.py @@ -130,7 +130,7 @@ def find_id_in_yaml(yaml_file: str, raw_id: str) -> list[types.Location]: return [] try: - with open(yaml_file) as f: + with open(yaml_file, encoding="utf-8") as f: lines = f.readlines() except OSError: return [] @@ -160,7 +160,7 @@ def _find_reference_in_yaml(yaml_file: str, raw_id: str) -> list[types.Location] return [] try: - with open(yaml_file) as f: + with open(yaml_file, encoding="utf-8") as f: lines = f.readlines() except OSError: return [] diff --git a/src/reqstool/lsp/root_discovery.py b/src/reqstool/lsp/root_discovery.py index 62bdbd30..d8259e64 100644 --- a/src/reqstool/lsp/root_discovery.py +++ b/src/reqstool/lsp/root_discovery.py @@ -67,7 +67,7 @@ def _read_ignore_patterns(dirpath: str) -> list[str] | None: if not os.path.exists(ignore_file): return None try: - with open(ignore_file) as f: + with open(ignore_file, encoding="utf-8") as f: patterns = [line.strip() for line in f if line.strip() and not line.strip().startswith("#")] except OSError: return None @@ -101,7 +101,7 @@ def _quick_parse(req_dir: str) -> DiscoveredProject | None: req_file = os.path.join(req_dir, "requirements.yml") yaml = YAML() try: - with open(req_file) as f: + with open(req_file, encoding="utf-8") as f: data = yaml.load(f) except Exception as e: logger.warning("Failed to parse %s: %s", req_file, e) diff --git a/src/reqstool/lsp/server.py b/src/reqstool/lsp/server.py index 21c1c940..d6d52d21 100644 --- a/src/reqstool/lsp/server.py +++ b/src/reqstool/lsp/server.py @@ -392,12 +392,16 @@ def _publish_all_diagnostics(ls: ReqstoolLanguageServer) -> None: _publish_diagnostics_for_document(ls, uri) -def start_server(tcp: bool = False, host: str = "127.0.0.1", port: int = 2087, log_file: str | None = None) -> None: - """Entry point for `reqstool lsp` command.""" +def _log_handlers(log_file: str | None) -> list[logging.Handler]: handlers: list[logging.Handler] = [logging.StreamHandler()] if log_file: - handlers.append(logging.FileHandler(log_file)) - logging.basicConfig(level=logging.INFO, handlers=handlers, force=True) + handlers.append(logging.FileHandler(log_file, encoding="utf-8")) + return handlers + + +def start_server(tcp: bool = False, host: str = "127.0.0.1", port: int = 2087, log_file: str | None = None) -> None: + """Entry point for `reqstool lsp` command.""" + logging.basicConfig(level=logging.INFO, handlers=_log_handlers(log_file), force=True) try: if tcp: logger.info("Starting reqstool LSP server (TCP %s:%d)", host, port) diff --git a/src/reqstool/lsp/yaml_schema.py b/src/reqstool/lsp/yaml_schema.py index e537e0a2..aecf6c4f 100644 --- a/src/reqstool/lsp/yaml_schema.py +++ b/src/reqstool/lsp/yaml_schema.py @@ -23,7 +23,7 @@ def load_schema(schema_name: str) -> dict | None: schema_path = os.path.join(SCHEMA_DIR, schema_name) try: - with open(schema_path) as f: + with open(schema_path, encoding="utf-8") as f: return json.load(f) except (OSError, json.JSONDecodeError) as e: logger.warning("Failed to load schema %s: %s", schema_name, e) diff --git a/tests/unit/reqstool/test_command.py b/tests/unit/reqstool/test_command.py index 26e41baa..dea0c067 100644 --- a/tests/unit/reqstool/test_command.py +++ b/tests/unit/reqstool/test_command.py @@ -536,3 +536,81 @@ def test_report_to_stdout_is_utf8_under_legacy_locale(): assert result.returncode == 0, result.stderr.decode(errors="replace") assert _ZERO_WIDTH_SPACE in result.stdout.decode("utf-8") + + +# --------------------------------------------------------------------------- +# Standard streams are UTF-8 for every command (redirected Windows stdio is cp1252) +# --------------------------------------------------------------------------- + + +def _run_cli_with_cp1252_stdio(*cli_args, stdin=None): + """Run the CLI the way a redirected Windows console does: all three std streams strictly cp1252.""" + import os + import subprocess + + env = {**os.environ, "PYTHONUTF8": "0", "PYTHONIOENCODING": "cp1252"} + return subprocess.run( + [sys.executable, "-m", "reqstool.command", *cli_args], + capture_output=True, + input=stdin, + env=env, + cwd=os.getcwd(), + ) + + +def test_validate_to_stdout_is_utf8_with_cp1252_stdio(): + result = _run_cli_with_cp1252_stdio("validate", "local", "-p", _FIXTURE) + + assert result.returncode == 0, result.stderr.decode(errors="replace") + assert "⚠" in result.stdout.decode("utf-8") # U+26A0, not encodable in cp1252 + + +@pytest.mark.parametrize( + "cli_args", + [ + ("status",), + ("report", "--format", "asciidoc"), + ("report", "--format", "markdown"), + ("export",), + ], +) +def test_other_commands_to_stdout_do_not_depend_on_stdio_encoding(cli_args): + result = _run_cli_with_cp1252_stdio(*cli_args, "local", "-p", _FIXTURE) + + assert b"UnicodeEncodeError" not in result.stderr, result.stderr.decode(errors="replace") + assert result.stdout.strip() + + +def test_enrich_reads_stdin_as_utf8_with_cp1252_stdio(): + # "Á" is C3 81 in UTF-8; 0x81 is undefined in cp1252, so decoding stdin with that codec fails. + text = "Á – ✓\n".encode("utf-8") + + result = _run_cli_with_cp1252_stdio("enrich", "--preset", "openspec:spec", "local", "-p", _FIXTURE, stdin=text) + + assert result.returncode == 0, result.stderr.decode(errors="replace") + assert result.stdout == text + + +def test_use_utf8_standard_streams_reconfigures_legacy_streams(monkeypatch): + from reqstool.command import _use_utf8_standard_streams + + streams = {name: io.TextIOWrapper(io.BytesIO(), encoding="cp1252") for name in ("stdin", "stdout", "stderr")} + for name, stream in streams.items(): + monkeypatch.setattr(sys, name, stream) + + _use_utf8_standard_streams() + + assert {name: stream.encoding for name, stream in streams.items()} == { + "stdin": "utf-8", + "stdout": "utf-8", + "stderr": "utf-8", + } + + +def test_use_utf8_standard_streams_tolerates_streams_that_cannot_be_reconfigured(monkeypatch): + from reqstool.command import _use_utf8_standard_streams + + for name in ("stdin", "stdout", "stderr"): + monkeypatch.setattr(sys, name, io.StringIO()) + + _use_utf8_standard_streams() # must not raise diff --git a/tests/unit/reqstool/test_default_encoding.py b/tests/unit/reqstool/test_default_encoding.py new file mode 100644 index 00000000..312ad432 --- /dev/null +++ b/tests/unit/reqstool/test_default_encoding.py @@ -0,0 +1,132 @@ +# Copyright © LFV + +"""Text files are UTF-8, whatever the platform default encoding is. + +On Windows ``open()`` without ``encoding=`` uses the ANSI code page (cp1252), so UTF-8 files written by editors or by +reqstool itself decode as mojibake or fail. These tests make the platform default strict ASCII, which rejects every +non-ASCII byte the same way, and then read non-ASCII UTF-8 files. +""" + +import builtins +import logging +import pathlib + +import pytest + +NON_ASCII = "Måste stödja ✓ – ändå" + + +def _default_to_ascii(real): + def wrapper(file, mode="r", *args, **kwargs): + if "b" not in mode and kwargs.get("encoding") is None and len(args) < 2: + kwargs["encoding"] = "ascii" + return real(file, mode, *args, **kwargs) + + return wrapper + + +@pytest.fixture +def ascii_default_encoding(monkeypatch): + """Return a function that makes ``open()`` default to ASCII inside the given module.""" + + def apply(module): + monkeypatch.setattr(module, "open", _default_to_ascii(builtins.open), raising=False) + + return apply + + +def test_lsp_schema_is_read_as_utf8(tmp_path, monkeypatch, ascii_default_encoding): + from reqstool.lsp import yaml_schema + + (tmp_path / "x.schema.json").write_text(f'{{"title": "{NON_ASCII}"}}', encoding="utf-8") + monkeypatch.setattr(yaml_schema, "SCHEMA_DIR", str(tmp_path)) + ascii_default_encoding(yaml_schema) + + assert yaml_schema.load_schema("x.schema.json") == {"title": NON_ASCII} + + +def test_lsp_definition_finds_id_in_utf8_yaml(tmp_path, ascii_default_encoding): + from reqstool.lsp.features import definition + + yaml_file = tmp_path / "requirements.yml" + yaml_file.write_text(f"requirements:\n - title: {NON_ASCII}\n - id: REQ_001\n", encoding="utf-8") + ascii_default_encoding(definition) + + locations = definition.find_id_in_yaml(str(yaml_file), "REQ_001") + + assert [loc.range.start.line for loc in locations] == [2] + + +def test_lsp_definition_finds_reference_in_utf8_yaml(tmp_path, ascii_default_encoding): + from reqstool.lsp.features import definition + + yaml_file = tmp_path / "software_verification_cases.yml" + yaml_file.write_text(f"cases:\n - description: {NON_ASCII}\n requirement_ids: [REQ_001]\n", encoding="utf-8") + ascii_default_encoding(definition) + + locations = definition._find_reference_in_yaml(str(yaml_file), "REQ_001") + + assert [loc.range.start.line for loc in locations] == [2] + + +def test_root_discovery_reads_utf8_ignore_file(tmp_path, ascii_default_encoding): + from reqstool.lsp import root_discovery + + (tmp_path / ".reqstoolignore").write_text(f"# {NON_ASCII}\nbuild\n", encoding="utf-8") + ascii_default_encoding(root_discovery) + + assert root_discovery._read_ignore_patterns(str(tmp_path)) == ["build"] + + +def test_root_discovery_parses_utf8_requirements_file(tmp_path, ascii_default_encoding): + from reqstool.lsp import root_discovery + + (tmp_path / "requirements.yml").write_text( + f"metadata:\n urn: ms-001\n variant: microservice\n title: {NON_ASCII}\n", encoding="utf-8" + ) + ascii_default_encoding(root_discovery) + + project = root_discovery._quick_parse(str(tmp_path)) + + assert project is not None + assert project.urn == "ms-001" + + +def test_reqstool_ai_config_is_read_as_utf8(tmp_path, ascii_default_encoding): + from reqstool.common import reqstool_ai_config + + config = tmp_path / ".reqstool-ai.yaml" + config.write_text(f"# {NON_ASCII}\nsystem:\n path: docs\n", encoding="utf-8") + ascii_default_encoding(reqstool_ai_config) + + assert reqstool_ai_config.resolve_system_path(config) == (tmp_path / "docs").resolve() + + +def test_json_schema_resource_is_read_as_utf8(monkeypatch): + from reqstool.common.validators.syntax_validator import JsonSchemaItem + + real_read_text = pathlib.Path.read_text + + def read_text_ascii_default(self, encoding=None, errors=None, newline=None): + return real_read_text(self, encoding=encoding or "ascii", errors=errors, newline=newline) + + monkeypatch.setattr(pathlib.Path, "read_text", read_text_ascii_default) + + # export_output.schema.json contains an em dash in a description + assert JsonSchemaItem("export_output.schema.json").schema["$schema"] + + +def test_lsp_log_file_is_written_as_utf8(tmp_path, ascii_default_encoding): + from reqstool.lsp.server import _log_handlers + + ascii_default_encoding(logging) + log_file = tmp_path / "lsp.log" + handlers = _log_handlers(str(log_file)) + try: + for handler in handlers: + handler.handle(logging.makeLogRecord({"msg": NON_ASCII, "levelno": logging.INFO, "levelname": "INFO"})) + finally: + for handler in handlers: + handler.close() + + assert NON_ASCII in log_file.read_text(encoding="utf-8")