Skip to content

Commit

Permalink
elidelong: command-line filter to elide long lines
Browse files Browse the repository at this point in the history
  • Loading branch information
hydrargyrum committed Oct 19, 2023
1 parent 0eff6e0 commit a3efe2e
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ This repository hosts various small personal tools.
- [`csv2json`](csv2json): transform CSV into JSON
- [`csv2table`](csv2table): pretty-print a CSV file with ASCII-art table
- [`dpkg-imediff`](dpkg-imediff): when dpkg interactively prompts for resolving a config file conflict, run this to start a merge editor
- [`elidelong`](elidelong): command-line filter to elide long lines
- [`exiforientergui`](exiforientergui): GUI to losslessly modify EXIF orientation of an image
- [`ffmcut`](ffmcut): ffmpeg wrapper to cut a video between 2 timestamps
- [`firefox-relay-tools/fxrelay-add`](firefox-relay-tools/fxrelay-add): add a Firefox Relay address
Expand Down
64 changes: 64 additions & 0 deletions elidelong/elidelong
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#!/usr/bin/env python3

# SPDX-License-Identifier: WTFPL

import argparse
import os
import signal
import sys
#import fileinput


def has_colors():
if os.environ.get("NO_COLOR"):
return False
if os.environ.get("CLICOLOR_FORCE") or os.environ.get("FORCE_COLOR"):
return True
return sys.stdout.isatty()


def main():
signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

parser = argparse.ArgumentParser()
parser.add_argument("-l", "--length", type=int, default=80)
parser.add_argument("file", default="-", nargs="?")
args = parser.parse_args()

if args.file == "-":
fp = sys.stdin
else:
fp = open(args.file)

with fp:
skip_until_nl = False
buf = ""
while True:
if not buf:
buf = fp.readline(args.length)
if not buf:
break

elif len(buf) < args.length:
buf += fp.readline(args.length - len(buf))

pos = buf.find("\n")
if pos >= 0:
if skip_until_nl:
buf = buf[pos + 1:]
else:
line, buf = buf[:pos], buf[pos + 1:]
print(line)
skip_until_nl = False

else:
if skip_until_nl:
buf = ""
else:
print(buf)
skip_until_nl = True


if __name__ == "__main__":
main()
43 changes: 43 additions & 0 deletions elidelong/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/bin/sh -eu
# SPDX-License-Identifier: WTFPL
# shellcheck enable=

cd "$(dirname "$0")"

got=$(mktemp sorted.XXXXXX)
trap 'rm "$got"' EXIT


init () {
./elidelong "$@" > "$got"
}

check () {
diff -u - "$got"
}


# basic test
init -l 4 <<- EOF
a
bc
def
ghij
klmno
pqrstu
vwxyz
012345
EOF

check <<- EOF
a
bc
def
ghij
klmn
pqrs
vwxy
0123
EOF

0 comments on commit a3efe2e

Please sign in to comment.