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
30 changes: 22 additions & 8 deletions termgraph/termgraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,23 @@ def init_args() -> dict:

def main():
"""Main function."""
try:
try:
_run()
finally:
# Flush even when argument parsing exits for --help or --version.
sys.stdout.flush()
except BrokenPipeError:
# Avoid another failed flush during interpreter shutdown.
devnull = os.open(os.devnull, os.O_WRONLY)
try:
os.dup2(devnull, sys.stdout.fileno())
finally:
os.close(devnull)
raise SystemExit(1) from None


def _run():
args = init_args()

if args["version"]:
Expand All @@ -106,14 +123,11 @@ def main():
data_obj = Data.from_file(args["filename"], args)
colors = _extract_colors(data_obj, args)

try:
if args["calendar"]:
# calendar_heatmap still uses old interface
calendar_heatmap(data_obj.data, data_obj.labels, args)
else:
chart(data_obj, args, colors)
except BrokenPipeError:
pass
if args["calendar"]:
# calendar_heatmap still uses old interface
calendar_heatmap(data_obj.data, data_obj.labels, args)
else:
chart(data_obj, args, colors)


def chart(data_obj: Data, args: dict, colors: list) -> None:
Expand Down
39 changes: 38 additions & 1 deletion tests/test_init.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,42 @@
import pytest

from termgraph import termgraph as tg


def test_init_args():
tg.init_args()
tg.init_args()


@pytest.mark.parametrize(
"rows,options",
[
(1, ["--width", "10"]),
(300, ["--width", "1000"]),
(1, ["--version"]),
(1, ["--help"]),
],
)
def test_cli_closed_stdout_pipe(tmp_path, rows, options):
"""Exercise interpreter shutdown too, not only errors raised inside draw."""
import os
import subprocess
import sys

# One small row fails at the final flush; many wide rows fail while drawing.
data_file = tmp_path / f"pipe-{rows}.dat"
data_file.write_text("item 1\n" * rows)
read_fd, write_fd = os.pipe()
os.close(read_fd)
try:
result = subprocess.run(
[sys.executable, "-m", "termgraph.termgraph", str(data_file), *options],
check=False,
stdout=write_fd,
stderr=subprocess.PIPE,
text=True,
timeout=15,
)
finally:
os.close(write_fd)
assert result.returncode == 1
assert result.stderr == ""
Loading