Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first commit for adding extract_if_need_be functionality #5

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions viashpy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,33 @@ def extract_tar(pathname: Path | str, output_dir: Path | str):
members_to_move = [mem for mem in members if mem.path != Path(".")]
open_tar.extractall(unpacked_path, members=members_to_move)
return unpacked_path

# helper function for cheching whether something is a gzip
def is_gz_file(path: Path) -> bool:
with open(path, "rb") as file:
return file.read(2) == b"\x1f\x8b"

# if {par_value} is a Path, extract it to a temp_dir_path and return the resulting path
def extract_if_need_be(pathname: Path | str, output_dir: Path | str) -> Path:
pathname, output_dir = Path(pathname), Path(output_dir)

if pathname.is_file() and tarfile.is_tarfile(pathname):
logger.info("Tar detected; extracting %s", pathname)
return extract_tar(pathname, output_dir)

elif pathname.is_file() and is_gz_file(pathname):
# Remove extension (if it exists)
extaction_file_name = Path(pathname.stem)
unpacked_path = output_dir / extaction_file_name
logger.info("Gzip detected; extracting %s", pathname)

import gzip
import shutil

with gzip.open(pathname, "rb") as f_in:
with open(unpacked_path, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
return unpacked_path

else:
return pathname