def extract_archive(
    archive_data: BinaryIO, target_directory: str, overwrite: bool = False
):
    """Extract a tar.gz archive (written for example via create_archive) from a bytes buffer
    into a target directory.

    Args:
        archive_data (BinaryIO): BinaryIO object ( typicall BytesIO or FileIO ) of the tar.gz archive to be extracted.
        target_directory (str): Target directory to extract to.
        overwrite (bool, optional): Whether to overwrite files or not.
                                    If False, files will be silently skipped
                                    if they already exist. Defaults to False.
    """
    archive = tarfile.open(fileobj=archive_data, mode="r:gz")

    # Extract the archive contents into the target directory
    for member in archive.getmembers():
        # Calculate the full path of the extracted file or directory
        target_path = os.path.join(target_directory, member.name)

        # Check if the file or directory already exists
        if os.path.exists(target_path):
            if not overwrite:
                _LOGGER.debug(
                    f"extract_archive: Skipping extraction of file to {os.path.abspath(target_path)}: A file at that path already exists, and overwrite is not enabled."
                )
                continue
            else:
                _LOGGER.debug(
                    f"extract_archive: Replacing existing file at {os.path.abspath(target_path)} with file from archive."
                )
                os.remove(target_path)

        # Extract the file or directory from the archive
        archive.extract(member, target_directory)

    # Close the archive object
    archive.close()
Extract a tar.gz archive (written for example via create_archive) from a bytes buffer
into a target directory.

Args:
archive_data (BinaryIO): BinaryIO object ( typicall BytesIO or FileIO ) of the tar.gz archive to be extracted.
target_directory (str): Target directory to extract to.
overwrite (bool, optional): Whether to overwrite files or not.
If False, files will be silently skipped
if they already exist. Defaults to False.
python/aitemplate/utils/io.py