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
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Unreleased
- Zsh completion scripts parse correctly on Windows. :issue:`3277`
- Shell completion of `Choice` `Enum` values produces a valid completion
result. :issue:`3015`
- Fix empty byte-string handling in echo. :issue:`3487`


Version 8.4.0
-------------
Expand Down
16 changes: 8 additions & 8 deletions src/click/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def __iter__(self) -> cabc.Iterator[t.AnyStr]:


def echo(
message: t.Any | None = None,
message: object = None,
file: t.IO[t.Any] | None = None,
nl: bool = True,
err: bool = False,
Expand Down Expand Up @@ -287,14 +287,15 @@ def echo(
if file is None:
return

# Convert non bytes/text into the native string type.
if message is not None and not isinstance(message, (str, bytes, bytearray)):
out: str | bytes | bytearray | None = str(message)
else:
out = message
match message:
case str() | bytes() | bytearray():
out = message
case None:
out = ""
case _:
out = str(message)

if nl:
out = out or ""
if isinstance(out, str):
out += "\n"
else:
Expand All @@ -310,7 +311,6 @@ def echo(
# would expect. Eg: you can write to StringIO for other cases.
if isinstance(out, (bytes, bytearray)):
binary_file = _find_binary_writer(file)

if binary_file is not None:
file.flush()
binary_file.write(out)
Expand Down
5 changes: 5 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from decimal import Decimal
from fractions import Fraction
from functools import partial
from io import BytesIO
from io import StringIO
from unittest.mock import patch

Expand Down Expand Up @@ -97,6 +98,10 @@ def test_echo_custom_file():
click.echo("hello", file=f)
assert f.getvalue() == "hello\n"

b = BytesIO()
click.echo(b"", b)
assert b.getvalue() == b"\n"


def test_echo_no_streams(monkeypatch, runner):
"""echo should not fail when stdout and stderr are None with pythonw on Windows."""
Expand Down
Loading