28
28
import os
29
29
30
30
import _compression
31
+ import sys
31
32
32
33
from . import isal_zlib
33
34
34
- __all__ = ["IGzipFile" , "open" , "compress" , "decompress" ]
35
+ __all__ = ["IGzipFile" , "open" , "compress" , "decompress" , "BadGzipFile" ]
35
36
36
37
_COMPRESS_LEVEL_FAST = isal_zlib .ISAL_BEST_SPEED
37
38
_COMPRESS_LEVEL_TRADEOFF = isal_zlib .ISAL_DEFAULT_COMPRESSION
40
41
41
42
BUFFER_SIZE = _compression .BUFFER_SIZE
42
43
44
+ class BadGzipFile (OSError ):
45
+ pass
46
+
43
47
44
48
# The open method was copied from the python source with minor adjustments.
45
49
def open (filename , mode = "rb" , compresslevel = _COMPRESS_LEVEL_TRADEOFF ,
@@ -225,7 +229,7 @@ def main():
225
229
parser .description = (
226
230
"A simple command line interface for the igzip module. "
227
231
"Acts like igzip." )
228
- parser .add_argument ("file" )
232
+ parser .add_argument ("file" , nargs = "?" )
229
233
compress_group = parser .add_mutually_exclusive_group ()
230
234
compress_group .add_argument (
231
235
"-0" , "--fast" , action = "store_const" , dest = "compresslevel" ,
@@ -251,24 +255,37 @@ def main():
251
255
252
256
compresslevel = args .compresslevel or _COMPRESS_LEVEL_TRADEOFF
253
257
254
- if args .compress :
255
- out_filename = args .file + ".gz"
256
- out_open = functools .partial (open , compresslevel = compresslevel )
257
- in_open = io .open
258
+ if args .file is None :
259
+ if args .compress :
260
+ in_file = sys .stdin .buffer
261
+ out_file = IGzipFile (mode = "wb" , compresslevel = compresslevel ,
262
+ fileobj = sys .stdout .buffer )
263
+ else :
264
+ in_file = IGzipFile (mode = "rb" , fileobj = sys .stdin .buffer )
265
+ out_file = sys .stdout .buffer
258
266
else :
259
- base , extension = os .path .splitext (args .file )
260
- if extension != ".gz" :
261
- raise ValueError ("Can only decompress files with a .gz extension" )
262
- out_filename = base
263
- out_open = io .open
264
- in_open = open
265
- with in_open (args .file , "rb" ) as in_file :
266
- with out_open (out_filename , "wb" ) as out_file :
267
- while True :
268
- block = in_file .read (_BLOCK_SIZE )
269
- if block == b"" :
270
- break
271
- out_file .write (block )
267
+ if args .compress :
268
+ in_file = io .open (args .file , mode = "rb" )
269
+ out_file = open (args .file + ".gz" , mode = "wb" ,
270
+ compresslevel = compresslevel )
271
+ else :
272
+ base , extension = os .path .splitext (args .file )
273
+ if extension != ".gz" :
274
+ print (f"filename doesn't end in .gz: { args .file } " )
275
+ return
276
+ in_file = open (args .file , "rb" )
277
+ out_file = io .open (base , "wb" )
278
+ try :
279
+ while True :
280
+ block = in_file .read (_BLOCK_SIZE )
281
+ if block == b"" :
282
+ break
283
+ out_file .write (block )
284
+ finally :
285
+ if in_file is not sys .stdin .buffer :
286
+ in_file .close ()
287
+ if out_file is not sys .stdout .buffer :
288
+ out_file .close ()
272
289
273
290
274
291
if __name__ == "__main__" :
0 commit comments