-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsponge
executable file
·83 lines (68 loc) · 2.65 KB
/
sponge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
# Copyright © 2022 Cobalt <[email protected]> under the MIT license
# See either the LICENSE file in https://github.com/Chaostheorie/sponge or https://mit-license.org/
import sys
from tempfile import TemporaryFile
if __name__ == "__main__":
if sys.argv[-1] in ["--help", "-h"]:
print(
"""Usage: sponge [OPTION]... [FILE]
Read full stdin input (until EOF) and write to FILE
-h, --help Print this help message
-t Buffer stdin output in tmp file before writing
-e Read from stderr instead of stdin"""
)
sys.exit(0)
# Parse args
arg_number = len(sys.argv)
# Check if destination is specified
if arg_number == 1:
print(
"You need to specify a destination file. See 'sponge --help' for usage information"
)
sys.exit(1)
else:
source = sys.stdin
buffered = False
# Check if flag for alternative input or buffering in tmp file was set
if arg_number > 2:
for i in range(1, arg_number):
if sys.argv[i] == "-e":
source = sys.stderr
if sys.argv[i] == "-t":
buffered = True
# Optional buffering of stdin in tmp file
if buffered:
# Read data in chunks and write to tmp file
tmp_buffer = TemporaryFile()
data = None
# Read from stdin and write chunks to tmp file
with source as sf:
while True:
data = sf.buffer.read(1024)
if data == b"":
break
else:
tmp_buffer.write(data)
# Flush buffer and return to start of tmp file
tmp_buffer.flush()
tmp_buffer.seek(0)
# Clear and/ or create file
destination = open(sys.argv[-1], "wb+")
destination.write(b"")
destination.close()
# Open in append mode to allow chunked writing from tmp file
with open(sys.argv[-1], "ab") as destination:
data = tmp_buffer.read(1024)
# Write until all contents of tmp file are read
while data != b"":
destination.write(data)
data = tmp_buffer.read(1024)
# Close tmp file
tmp_buffer.close()
else:
# Slurp data from source
data = source.buffer.read()
# Write data to destination
with open(sys.argv[-1], "wb") as destination:
destination.write(data)