From 05a36eb483e5f60fa2c6cbac28e5aec018e8f3a7 Mon Sep 17 00:00:00 2001 From: Ville Rantanen Date: Thu, 24 Aug 2023 15:26:37 +0300 Subject: [PATCH] because why not --- files/sponge | 74 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 59 insertions(+), 15 deletions(-) diff --git a/files/sponge b/files/sponge index 7bf1e17..88f10f7 100755 --- a/files/sponge +++ b/files/sponge @@ -1,25 +1,69 @@ #!/usr/bin/env python3 import sys +import time from argparse import ArgumentParser -# Set up options -parser=ArgumentParser(description="Sponge file before writing output: grep foo file.txt | sponge file.txt", - epilog="This tool is a modification from http://joeyh.name/code/moreutils/ with the same name.") -parser.add_argument("-a",action="store_true",dest="append",default=False, - help="Append to file instead of overwriting") -parser.add_argument(type=str,dest="file", - help="File to write to") -options=parser.parse_args() -# Read data -data=sys.stdin.read() +class Verbose: + def __init__(self): + self.progress_chars = " ▏▎▍▌▋▊▉█" + self.progress_n = 0 + self.ts = 0 + self.loops = 0 + + def next(self): + if time.time() > self.ts + 0.1: + s = ( + " " + + self.loops * self.progress_chars[-1] + + self.progress_chars[self.progress_n] + + "\r" + ) + print(s, file=sys.stderr, end="") + self.progress_n = (1 + self.progress_n) % len(self.progress_chars) + if self.progress_n == 0: + self.loops += 1 + if self.loops >= 10: + print(" " * 11 + "\r", file=sys.stderr, end="") + self.loops = 0 + sys.stderr.flush() + self.ts = time.time() + + +# Set up options +parser = ArgumentParser( + description="Sponge file before writing output: grep foo file.txt | sponge file.txt", + epilog="This tool is a modification from http://joeyh.name/code/moreutils/ with the same name.", +) +parser.add_argument( + "-a", + action="store_true", + dest="append", + default=False, + help="Append to file instead of overwriting", +) +parser.add_argument( + "-v", action="store_true", dest="verbose", default=False, help="Progress to stderr" +) +parser.add_argument(type=str, dest="file", help="File to write to") +options = parser.parse_args() + # choose mode -mode="w" +mode = "wb" if options.append: - mode="a" + mode = "ab" +if options.verbose: + v = Verbose() +chunk_size = 1024 * 1024 * 1 # Mb + # Write the file -writer=open(options.file, mode) -writer.write(data) -writer.close() +with open(options.file, mode) as writer: + while True: + chunk = sys.stdin.buffer.read(chunk_size) + if not chunk: + break + if options.verbose: + v.next() + writer.write(chunk)