Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/reqstool/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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()

Expand Down
2 changes: 1 addition & 1 deletion src/reqstool/common/reqstool_ai_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion src/reqstool/common/validators/syntax_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/reqstool/lsp/features/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
Expand Down Expand Up @@ -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 []
Expand Down
4 changes: 2 additions & 2 deletions src/reqstool/lsp/root_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 8 additions & 4 deletions src/reqstool/lsp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/reqstool/lsp/yaml_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
78 changes: 78 additions & 0 deletions tests/unit/reqstool/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
132 changes: 132 additions & 0 deletions tests/unit/reqstool/test_default_encoding.py
Original file line number Diff line number Diff line change
@@ -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")
Loading