Skip to content
Open
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
25 changes: 25 additions & 0 deletions markdown_it/cli/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
52 changes: 52 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,58 @@ def test_stdin():
assert string_io.getvalue() == "<h1>a b c</h1>\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") == "<h1>ʤ ✓</h1>\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") == "<h1>Łódź</h1>\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"<p>abc</p>\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") == "<h1>a</h1>\n"


def test_multiple_files():
with tempfile.TemporaryDirectory() as tempdir:
path1 = pathlib.Path(tempdir).joinpath("test1.md")
Expand Down