Skip to content

extract_archive

extract_archive(file: str, target_dir: str, overwrite=True)

Extract archive file.

Code borrowed from dgl

Parameters:

Name Type Description Default
file str

Absolute path of the archive file.

required
target_dir str

Target directory of the archive to be uncompressed.

required
overwrite

Whether to overwrite the contents inside the directory. By default always overwrites.

True
Source code in mlx_graphs/datasets/utils/download.py
def extract_archive(file: str, target_dir: str, overwrite=True):
    """Extract archive file.

    Code borrowed from dgl

    Args:
        file: Absolute path of the archive file.
        target_dir: Target directory of the archive to be uncompressed.
        overwrite: Whether to overwrite the contents inside the directory.
            By default always overwrites.
    """
    if os.path.exists(target_dir) and not overwrite:
        return
    print("Extracting file to {}".format(target_dir))
    if file.endswith(".tar.gz") or file.endswith(".tar") or file.endswith(".tgz"):
        import tarfile

        with tarfile.open(file, "r") as archive:
            abs_target = os.path.abspath(target_dir)

            def is_within_target(path: str) -> bool:
                # `commonpath` compares whole path components: unlike a
                # string prefix, "<target>_evil" is not inside "<target>".
                path = os.path.abspath(path)
                return os.path.commonpath([abs_target, path]) == abs_target

            for member in archive.getmembers():
                member_path = os.path.join(abs_target, member.name)
                if not is_within_target(member_path):
                    raise Exception("Attempted Path Traversal in Tar File")
                # Links must not point outside either: files extracted later
                # could be written through them.
                if member.issym() or member.islnk():
                    base = (
                        os.path.dirname(member_path) if member.issym() else abs_target
                    )
                    if not is_within_target(os.path.join(base, member.linkname)):
                        raise Exception("Attempted Path Traversal in Tar File")
            if hasattr(tarfile, "data_filter"):  # Python >= 3.12 and backports
                archive.extractall(target_dir, filter="data")  # nosec B202
            else:  # members validated above
                archive.extractall(target_dir)  # nosec B202
    elif file.endswith(".gz"):
        import gzip
        import shutil

        with gzip.open(file, "rb") as f_in:
            target_file = os.path.join(target_dir, os.path.basename(file)[:-3])
            with open(target_file, "wb") as f_out:
                shutil.copyfileobj(f_in, f_out)
    elif file.endswith(".zip"):
        import zipfile

        with zipfile.ZipFile(file, "r") as archive:
            abs_target = os.path.abspath(target_dir)
            for name in archive.namelist():
                member_path = os.path.abspath(os.path.join(target_dir, name))
                if os.path.commonpath([abs_target, member_path]) != abs_target:
                    raise Exception("Attempted Path Traversal in Zip File")
            archive.extractall(path=target_dir)  # nosec B202 - members validated above
    else:
        raise Exception("Unrecognized file type: " + file)

from mlx_graphs.datasets.utils import extract_archive · mlx_graphs/datasets/utils/download.py