Skip to content

Commit 2f2449d

Browse files
committed
fix(cli): add entrypoint and utf-8 output
Refs #379, #383.
1 parent 614b019 commit 2f2449d

3 files changed

Lines changed: 29 additions & 1 deletion

File tree

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ Documentation = "https://mistune.lepture.com/"
3535
Source = "https://github.com/lepture/mistune"
3636
Donate = "https://github.com/sponsors/lepture"
3737

38+
[project.scripts]
39+
mistune = "mistune.__main__:cli"
40+
3841
[build-system]
3942
requires = ["setuptools"]
4043
build-backend = "setuptools.build_meta"

src/mistune/__main__.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,10 @@ def _md(args: argparse.Namespace) -> "Markdown":
3535

3636
def _output(text: str, args: argparse.Namespace) -> None:
3737
if args.output:
38-
with open(args.output, "w") as f:
38+
with open(args.output, "w", encoding="utf-8") as f:
3939
f.write(text)
4040
else:
41+
_ensure_stdout_utf8()
4142
print(text)
4243

4344

@@ -123,6 +124,12 @@ def cli() -> None:
123124
sys.exit(1)
124125

125126

127+
def _ensure_stdout_utf8() -> None:
128+
reconfigure = getattr(sys.stdout, "reconfigure", None)
129+
if reconfigure is not None:
130+
reconfigure(encoding="utf-8")
131+
132+
126133
def read_stdin() -> Optional[str]:
127134
is_stdin_pipe = not sys.stdin.isatty()
128135
if is_stdin_pipe:

tests/test_misc.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,3 +309,21 @@ def test_def_list_plugin_redos_candidate(self):
309309
md = mistune.create_markdown(escape=False, plugins=["def_list"])
310310
result = md("x\n" * 8000)
311311
self.assertTrue(result.startswith("<p>x\nx\n"))
312+
313+
def test_cli_output_file_uses_utf8(self):
314+
from argparse import Namespace
315+
from pathlib import Path
316+
from tempfile import TemporaryDirectory
317+
318+
from mistune.__main__ import _output
319+
320+
with TemporaryDirectory() as tmpdir:
321+
path = Path(tmpdir) / "out.html"
322+
_output("★", Namespace(output=str(path)))
323+
self.assertEqual(path.read_text(encoding="utf-8"), "★")
324+
325+
def test_project_script_entrypoint(self):
326+
from pathlib import Path
327+
328+
pyproject = Path("pyproject.toml").read_text(encoding="utf-8")
329+
self.assertIn('mistune = "mistune.__main__:cli"', pyproject)

0 commit comments

Comments
 (0)