Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issue59: making exit more robust #60

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
39 changes: 26 additions & 13 deletions src/toolong/cli.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from importlib.metadata import version
import os
import sys

import click

Expand All @@ -22,6 +21,8 @@
)
def run(files: list[str], merge: bool, output_merge: str) -> None:
"""View / tail / search log files."""
import sys

stdin_tty = sys.__stdin__.isatty()
if not files and stdin_tty:
ctx = click.get_current_context()
Expand All @@ -38,11 +39,14 @@ def run(files: list[str], merge: bool, output_merge: str) -> None:
import selectors
import subprocess
import tempfile
import sys
import os

def request_exit(*args) -> None:
"""Don't write anything when a signal forces an error."""
sys.stderr.write("^C")
def request_exit(signum, frame) -> None:
"""Gracefully handle termination signals."""
sys.exit(0)

# Handle termination signals more gracefully
signal.signal(signal.SIGINT, request_exit)
signal.signal(signal.SIGTERM, request_exit)

Expand All @@ -61,16 +65,25 @@ def request_exit(*args) -> None:
env={**os.environ, "TEXTUAL_ALLOW_SIGNALS": "1"},
) as process:

# Current process copies from stdin to the temp file
# Selector to monitor stdin for read events
selector = selectors.SelectSelector()
selector.register(sys.stdin.fileno(), selectors.EVENT_READ)

while process.poll() is None:
for _, event in selector.select(0.1):
if process.poll() is not None:
break
if event & selectors.EVENT_READ:
if line := os.read(sys.stdin.fileno(), 1024 * 64):
temp_file.write(line)
else:
try:
while process.poll() is None:
for _, event in selector.select(0.1):
if process.poll() is not None:
break
if event & selectors.EVENT_READ:
line = os.read(sys.stdin.fileno(), 1024 * 64)
if line:
temp_file.write(line)
else:
break
except KeyboardInterrupt:
request_exit(signal.SIGINT, None)

finally:
# Ensure the process is properly terminated
process.terminate()
process.wait()