# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/10_gzip.ipynb.

# %% auto 0
__all__ = ['ungzip', 'untar', 'ungz']

# %% ../nbs/10_gzip.ipynb 5
import os
from pathlib import Path

try: import gzip, shutil, tarfile
except: ...

# %% ../nbs/10_gzip.ipynb 7
from nlit import EXT_TAR, EXT_GZ, EXT_TAR_GZ

# %% ../nbs/10_gzip.ipynb 9
from .exts import isgz, istar, istargz, istarball, dropext

# %% ../nbs/10_gzip.ipynb 11
def ungzip(path: Path, hush: bool = True, exists_ok: bool = False, cleanup: bool = False) -> Path:
    if not isgz(path): 
        if hush: return
        raise ValueError(f'Path {path} does not end with .gz')
    
    file = dropext(path, EXT_GZ)
    if file.is_file() and not exists_ok:
        if hush: return
        raise FileExistsError(f'File {file} already exists')
    
    try:
        with gzip.open(path, 'rb') as gunzipped:
            with open(file, 'wb') as unzipped:
                shutil.copyfileobj(gunzipped, unzipped)
                
    except EOFError as err:
        if hush: return
        raise err
    
    if cleanup and file.is_dir() and path.is_dir: path.rmdir()
    return file

# %% ../nbs/10_gzip.ipynb 12
def untar(path: Path, hush: bool = True, exists_ok: bool = False, cleanup: bool = False) -> Path:
    if not istarball(path): 
        if hush: return
        raise ValueError(f'Path {path} does not end with .tar or .tar.gz')
    
    file = dropext(path, EXT_TAR if istar(path) else EXT_TAR_GZ)
    if file.is_file() and not exists_ok:
        if hush: return
        raise FileExistsError(f'File {file} already exists')
    
    try:
        with tarfile.open(path, 'rb') as tarball:
            tarball.extractall(odir := path.parent)
            tarball.close()
                
    except EOFError as err:
        if hush: return
        raise err
    
    if cleanup and odir.is_dir(): odir.rmdir()
    return odir

# %% ../nbs/10_gzip.ipynb 13
def ungz(path: Path, hush: bool = True, exists_ok: bool = False, cleanup: bool = False) -> str:
    if istargz(path):
        path = untar(path, hush, exists_ok, cleanup)
    elif isgz(path):
        path = ungzip(path, hush, exists_ok, cleanup)
    elif istar(path):
        path = untar(path, hush, exists_ok, cleanup)
    elif istarball(path):
        path = untar(path, hush, exists_ok, cleanup)
    return path
