def serialize()

in antlir/compiler/procfs_serde.py [0:0]


def serialize(data: Any, subvol, path_with_ext: str) -> None:
    """
    Writes `data` to `path_with_ext` inside `subvol`.  The extension
    part of `path_with_ext` determines the serialization mechanism.

    Fails if the output file or directory exists.  Creates files with mode
    0644, directories with mode 0755.  Both get root:root ownership.
    """
    if data is None:
        return  # Write nothing, `None` corresponds to the "no such file".

    _, ext = os.path.splitext(path_with_ext)
    assert isinstance(ext, str)
    trailing_newline = b"\n"
    if ext in (".image_path", ".host_path"):
        if not isinstance(data, (str, bytes)):
            raise AssertionError(
                f"{path_with_ext} needs str/bytes, got {data} / {type(data)}"
            )
    elif ext == ".bin":
        trailing_newline = b""
        if not isinstance(data, bytes):
            raise AssertionError(
                f"{path_with_ext} needs bytes, got {data} / {type(data)}"
            )
    elif ext != "":
        raise AssertionError(f"Unsupported extension {path_with_ext}")

    if isinstance(data, dict):
        subvol.run_as_root(
            _make_script(
                subvol.path(path_with_ext),
                [
                    # Lacks -p since we want to fail if the dir exists
                    'mkdir --mode=0755 "$dest"'
                ],
            )
        )
        for k, v in data.items():
            serialize(v, subvol, os.path.join(path_with_ext, k))
        return

    if isinstance(data, bool):  # bool is a subclass of int, so check this first
        out_bytes = str(int(data)).encode()
    elif isinstance(data, (str, int, float)):
        out_bytes = str(data).encode()
    elif isinstance(data, bytes):
        out_bytes = data
    elif isinstance(data, list):
        raise AssertionError("add list support if you need it")
    else:
        raise AssertionError(f"unhandled type {type(data)} {data}")

    subvol.run_as_root(
        _make_script(subvol.path(path_with_ext), ['cat > "$dest"']),
        input=(out_bytes + trailing_newline),
    )