Skip to content

Commit

Permalink
Merge pull request #537 from janosh/fix-decompress_file
Browse files Browse the repository at this point in the history
Fix `decompress_file()` if no compressed file found
  • Loading branch information
shyuep committed Aug 8, 2023
2 parents 02340e4 + 94cd0da commit 63f7d30
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
13 changes: 6 additions & 7 deletions monty/shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,28 +93,27 @@ def compress_dir(path, compression="gz"):
compress_file(os.path.join(parent, f), compression=compression)


def decompress_file(filepath) -> str:
def decompress_file(filepath) -> str | None:
"""
Decompresses a file with the correct extension. Automatically detects
gz, bz2 or z extension.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
Returns:
str: The decompressed file path.
"""
toks = filepath.split(".")
file_ext = toks[-1].upper()
if file_ext in ["BZ2", "GZ", "Z"]:
out_file = ".".join(toks[0:-1])
with zopen(filepath, "rb") as f_in, open(out_file, "wb") as f_out:
if file_ext in ["BZ2", "GZ", "Z"] and os.path.isfile(filepath):
decompressed_file = ".".join(toks[0:-1])
with zopen(filepath, "rb") as f_in, open(decompressed_file, "wb") as f_out:
f_out.writelines(f_in)
os.remove(filepath)

return out_file
return decompressed_file
return None


def decompress_dir(path):
Expand Down
5 changes: 5 additions & 0 deletions tests/test_shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ def test_compress_and_decompress_file(self):
self.assertEqual(txt, "hello world")
self.assertRaises(ValueError, compress_file, "whatever", "badformat")

# test decompress non-existent/non-compressed file
self.assertIsNone(decompress_file("non-existent"))
self.assertIsNone(decompress_file("non-existent.gz"))
self.assertIsNone(decompress_file("non-existent.bz2"))

def tearDown(self):
os.remove(os.path.join(test_dir, "tempfile"))

Expand Down

0 comments on commit 63f7d30

Please sign in to comment.