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
7 changes: 7 additions & 0 deletions ansi2html/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.

import io
import optparse
import re
import sys
Expand Down Expand Up @@ -786,6 +787,12 @@ def main() -> None:
title=opts.output_title,
)

if hasattr(sys.stdin, "detach") and not isinstance(
sys.stdin, io.StringIO
): # e.g. during tests
input_buffer = sys.stdin.detach() # type: ignore
sys.stdin = io.TextIOWrapper(input_buffer, opts.input_encoding, "replace")

def _print(output_unicode: str, end: str = "\n") -> None:
if hasattr(sys.stdout, "buffer"):
output_bytes = (output_unicode + end).encode(opts.output_encoding)
Expand Down
31 changes: 30 additions & 1 deletion tests/test_ansi2html.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import textwrap
from io import StringIO
from os.path import abspath, dirname, join
from subprocess import run
from subprocess import PIPE, Popen, run
from typing import List

from mock import patch
Expand Down Expand Up @@ -470,6 +470,35 @@ def test_command_script(self) -> None:
result = run(["ansi2html", "--version"], check=True)
assert result.returncode == 0

def test_command_input_output_encoding(self) -> None:
input_encoding = "utf-16"
input_bytes = "regular \033[31mred\033[0m regular".encode(input_encoding)
output_encoding = "utf-32"
output_bytes_expected = (
'regular <span style="color: #aa0000">red</span> regular\n'.encode(
output_encoding
)
)

with Popen(
[
"ansi2html",
"--inline",
f"--input-encoding={input_encoding}",
f"--output-encoding={output_encoding}",
],
stdin=PIPE,
stdout=PIPE,
) as process:
assert process.stdin # for mypy
assert process.stdout # for mypy
process.stdin.write(input_bytes)
process.stdin.close()
stdout_bytes_actual = process.stdout.read()

assert stdout_bytes_actual == output_bytes_expected
assert process.returncode == 0

def test_command_module(self) -> None:
result = run(["python3", "-m", "ansi2html", "--version"], check=True)
assert result.returncode == 0