|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | from importlib.metadata import version |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
4 | 7 | import click |
5 | 8 |
|
6 | 9 | from toolong.ui import UI |
|
19 | 22 | ) |
20 | 23 | def run(files: list[str], merge: bool, output_merge: str) -> None: |
21 | 24 | """View / tail / search log files.""" |
22 | | - if not files: |
| 25 | + stdin_tty = sys.__stdin__.isatty() |
| 26 | + if not files and stdin_tty: |
23 | 27 | ctx = click.get_current_context() |
24 | 28 | click.echo(ctx.get_help()) |
25 | 29 | ctx.exit() |
26 | | - ui = UI(files, merge=merge, save_merge=output_merge) |
27 | | - ui.run() |
| 30 | + if stdin_tty: |
| 31 | + try: |
| 32 | + ui = UI(files, merge=merge, save_merge=output_merge) |
| 33 | + ui.run() |
| 34 | + except Exception: |
| 35 | + pass |
| 36 | + else: |
| 37 | + import signal |
| 38 | + import selectors |
| 39 | + import subprocess |
| 40 | + import tempfile |
| 41 | + |
| 42 | + def request_exit(*args) -> None: |
| 43 | + """Don't write anything when a signal forces an error.""" |
| 44 | + sys.stderr.write("^C") |
| 45 | + |
| 46 | + signal.signal(signal.SIGINT, request_exit) |
| 47 | + signal.signal(signal.SIGTERM, request_exit) |
| 48 | + |
| 49 | + # Write piped data to a temporary file |
| 50 | + with tempfile.NamedTemporaryFile( |
| 51 | + mode="w+b", buffering=0, prefix="tl_" |
| 52 | + ) as temp_file: |
| 53 | + |
| 54 | + # Get input directly from /dev/tty to free up stdin |
| 55 | + with open("/dev/tty", "rb", buffering=0) as tty_stdin: |
| 56 | + # Launch a new process to render the UI |
| 57 | + with subprocess.Popen( |
| 58 | + [sys.argv[0], temp_file.name], |
| 59 | + stdin=tty_stdin, |
| 60 | + close_fds=True, |
| 61 | + env={**os.environ, "TEXTUAL_ALLOW_SIGNALS": "1"}, |
| 62 | + ) as process: |
| 63 | + |
| 64 | + # Current process copies from stdin to the temp file |
| 65 | + selector = selectors.SelectSelector() |
| 66 | + selector.register(sys.stdin.fileno(), selectors.EVENT_READ) |
| 67 | + |
| 68 | + while process.poll() is None: |
| 69 | + for _, event in selector.select(0.1): |
| 70 | + if process.poll() is not None: |
| 71 | + break |
| 72 | + if event & selectors.EVENT_READ: |
| 73 | + if line := os.read(sys.stdin.fileno(), 1024 * 64): |
| 74 | + temp_file.write(line) |
| 75 | + else: |
| 76 | + break |
0 commit comments