Skip to content

Commit

Permalink
fix(hr): Handle BrokenPipeError according to official recommendations
Browse files Browse the repository at this point in the history
  • Loading branch information
rumpelsepp committed Aug 13, 2024
1 parent 54b4749 commit c0f7574
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/hr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# SPDX-License-Identifier: Apache-2.0

import argparse
import os
import signal
import sys
from itertools import islice
from pathlib import Path
Expand Down Expand Up @@ -89,8 +91,16 @@ def main() -> None:
print(f"invalid file format: {e}", file=sys.stderr)
sys.exit(1)
# BrokenPipeError appears when stuff is piped to | head.
except (KeyboardInterrupt, BrokenPipeError):
pass
# This is not an error for hr.
except BrokenPipeError:
# https://docs.python.org/3/library/signal.html#note-on-sigpipe
# Python flushes standard streams on exit; redirect remaining output
# to devnull to avoid another BrokenPipeError at shutdown.
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
sys.exit(0)
except KeyboardInterrupt:
sys.exit(128 + signal.SIGINT)


if __name__ == "__main__":
Expand Down
4 changes: 4 additions & 0 deletions tests/bats/100-hr.bats
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
run -1 bash -c "echo 'invalid json' | hr -"
}

@test "pipe to head and handle SIGPIPE" {
hr "$BATS_TEST_DIRNAME/testfiles/log-01.json.zst" | head
}

@test "filter priority" {
local additional_line
additional_line='{"module": "foo", "data": "I am the line!", "host": "kronos", "datetime":"2020-04-23T15:21:50.620310", "priority": 5, "version": 2}'
Expand Down

0 comments on commit c0f7574

Please sign in to comment.