from pathlib import Path
import io
import tarfile


def dir_to_blob(dir_path: Path) -> bytes:
    """
    Archive a directory and save it as a blob in-memory.
    Useful for storing a directory's contents in an in-memory object store.
    Use compression to reduce file size.  Extract with :func:`blob_to_dir`.

    Args:
      dir_path: Path to the directory to be archived.

    Returns:
      The compressed directory as a binary buffer.
    """
    blob = io.BytesIO()
    with tarfile.open(fileobj=blob, mode="w:gz") as archive:
        # Set arcname=. to ensure the files will be extracted properly
        # using relative paths
        archive.add(str(dir_path), arcname=".", recursive=True)

    # Seek the beginning of the buffer so we read the whole thing
    blob.seek(0)
    return blob.getvalue()