2828import os
2929
3030import _compression
31+ import sys
3132
3233from . import isal_zlib
3334
34- __all__ = ["IGzipFile" , "open" , "compress" , "decompress" ]
35+ __all__ = ["IGzipFile" , "open" , "compress" , "decompress" , "BadGzipFile" ]
3536
3637_COMPRESS_LEVEL_FAST = isal_zlib .ISAL_BEST_SPEED
3738_COMPRESS_LEVEL_TRADEOFF = isal_zlib .ISAL_DEFAULT_COMPRESSION
4041
4142BUFFER_SIZE = _compression .BUFFER_SIZE
4243
44+ class BadGzipFile (OSError ):
45+ pass
46+
4347
4448# The open method was copied from the python source with minor adjustments.
4549def open (filename , mode = "rb" , compresslevel = _COMPRESS_LEVEL_TRADEOFF ,
@@ -225,7 +229,7 @@ def main():
225229 parser .description = (
226230 "A simple command line interface for the igzip module. "
227231 "Acts like igzip." )
228- parser .add_argument ("file" )
232+ parser .add_argument ("file" , nargs = "?" )
229233 compress_group = parser .add_mutually_exclusive_group ()
230234 compress_group .add_argument (
231235 "-0" , "--fast" , action = "store_const" , dest = "compresslevel" ,
@@ -251,24 +255,37 @@ def main():
251255
252256 compresslevel = args .compresslevel or _COMPRESS_LEVEL_TRADEOFF
253257
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
258266 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 ()
272289
273290
274291if __name__ == "__main__" :
0 commit comments