diff --git a/markdown_it/cli/parse.py b/markdown_it/cli/parse.py index 9c1f2fb3..a8aeb0cc 100644 --- a/markdown_it/cli/parse.py +++ b/markdown_it/cli/parse.py @@ -8,7 +8,10 @@ import argparse from collections.abc import Iterable, Sequence +import io +import os import sys +from typing import TextIO from markdown_it import __version__ from markdown_it.main import MarkdownIt @@ -27,14 +30,36 @@ def main(args: Sequence[str] | None = None) -> int: if namespace.enable_tables: md.enable("table") if namespace.filenames: + _use_utf8(sys.stdout) convert(namespace.filenames, md) elif namespace.stdin: + # Read standard input like a file: UTF-8, ignoring undecodable bytes. + _use_utf8(sys.stdin, errors="ignore") + _use_utf8(sys.stdout) convert_stdin(md) else: interactive(md) return 0 +def _use_utf8(stream: TextIO, errors: str | None = None) -> None: + """Use UTF-8 for a redirected or piped standard stream. + + Files are read as UTF-8, but Python uses the locale encoding (e.g. cp1252 on + Windows) for standard streams that are not a terminal, so + ``markdown-it doc.md > doc.html`` raised UnicodeEncodeError for characters + outside it, and ``--stdin`` misread UTF-8 input. + An encoding set with PYTHONIOENCODING is kept, and a terminal is left as is. + """ + if ( + os.environ.get("PYTHONIOENCODING") + or not isinstance(stream, io.TextIOWrapper) + or stream.isatty() + ): + return + stream.reconfigure(encoding="utf-8", errors=errors or stream.errors) + + def convert(filenames: Iterable[str], md: MarkdownIt | None = None) -> None: for filename in filenames: convert_file(filename, md) diff --git a/tests/test_cli.py b/tests/test_cli.py index 450c862f..45175859 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -104,6 +104,58 @@ def test_stdin(): assert string_io.getvalue() == "

a b c

\n" +def _redirected(encoding: str, data: bytes = b"") -> io.TextIOWrapper: + """A standard stream redirected to a file or pipe, e.g. cp1252 on Windows.""" + return io.TextIOWrapper( + io.BytesIO(data), encoding=encoding, newline="\n", write_through=True + ) + + +def _written(stream: io.TextIOWrapper) -> bytes: + """The bytes written to a stream made by `_redirected`.""" + buffer = stream.buffer + assert isinstance(buffer, io.BytesIO) + return buffer.getvalue() + + +def test_redirected_stdout_gets_utf8(tmp_path, monkeypatch): + monkeypatch.delenv("PYTHONIOENCODING", raising=False) + path = tmp_path / "test.md" + path.write_text("# ʤ ✓", encoding="utf8") + stdout = _redirected("cp1252") + monkeypatch.setattr(sys, "stdout", stdout) + assert parse.main([str(path)]) == 0 + assert _written(stdout).decode("utf8") == "

ʤ ✓

\n" + + +def test_redirected_stdin_is_read_as_utf8(monkeypatch): + monkeypatch.delenv("PYTHONIOENCODING", raising=False) + monkeypatch.setattr(sys, "stdin", _redirected("cp1252", "# Łódź".encode())) + stdout = _redirected("cp1252") + monkeypatch.setattr(sys, "stdout", stdout) + assert parse.main(["--stdin"]) == 0 + assert _written(stdout).decode("utf8") == "

Łódź

\n" + + +def test_redirected_stdin_ignores_undecodable_bytes(monkeypatch): + monkeypatch.delenv("PYTHONIOENCODING", raising=False) + monkeypatch.setattr(sys, "stdin", _redirected("cp1252", b"\x80abc")) + stdout = _redirected("cp1252") + monkeypatch.setattr(sys, "stdout", stdout) + assert parse.main(["--stdin"]) == 0 + assert _written(stdout) == b"

abc

\n" + + +def test_redirected_stdout_keeps_pythonioencoding(tmp_path, monkeypatch): + monkeypatch.setenv("PYTHONIOENCODING", "utf-16") + path = tmp_path / "test.md" + path.write_text("# a", encoding="utf8") + stdout = _redirected("utf-16") + monkeypatch.setattr(sys, "stdout", stdout) + assert parse.main([str(path)]) == 0 + assert _written(stdout).decode("utf-16") == "

a

\n" + + def test_multiple_files(): with tempfile.TemporaryDirectory() as tempdir: path1 = pathlib.Path(tempdir).joinpath("test1.md")