Zip archives as streams (Effect's encoding/Zip).
encode writes each entry as it arrives and adds the central directory once the
input ends; decode reads entries in archive order from their local headers, so
an archive can be read as it arrives. decode never holds a whole body, at most 4
MiB of compressed input per entry, which is what these channels add to the blocking
zipfile, and encode only collects deflated bodies of at most 64 KiB.
Entries are stored or deflated, with ZIP64 fields when sizes, offsets or the entry count need them. Encryption, other compression methods and archives split across files are not supported.
Paths are returned as written in the archive: they can be absolute, contain ..,
drive letters, control characters or backslashes, and can repeat. Validate them
before writing entries to disk.
Types#
| Type | Definition | Description |
|---|---|---|
EntryType | type EntryType = Literal['File', 'Directory'] | |
Method | type Method = Literal['Store', 'Deflate'] | |
ZipErrorKind | type ZipErrorKind = Literal['InvalidHeader', 'InvalidData', 'Truncated', 'Checksum', 'SizeMismatch', 'Unsupported', 'BodyConsumed'] |
Classes#
Functions#
is_zip_error#
is_zip_error(value) -> TypeIs[ZipError]| Parameter | Type | Description |
|---|---|---|
value | object |
Returns TypeIs[ZipError]
def is_zip_error(value: object) -> TypeIs[ZipError]:
return isinstance(value, ZipError)file#
file(path, content, *, method='Deflate', mtime=None, mode=None) -> ContentEntryA file from in-memory content; a str is encoded as UTF-8. Use
method="Store" for content that is already compressed. Unset fields default
to an mtime of 1980-01-01T00:00:00Z, the earliest a zip header holds, and mode
0o644, which makes archives reproducible.
| Parameter | Type | Description |
|---|---|---|
path | str | |
content | str | bytes | |
method | Method = 'Deflate' | |
mtime | datetime | None = None | |
mode | int | None = None |
Returns ContentEntry
def file(
path: str,
content: str | bytes,
*,
method: Method = "Deflate",
mtime: datetime | None = None,
mode: int | None = None,
) -> ContentEntry:
"""A file from in-memory content; a ``str`` is encoded as UTF-8. Use
``method="Store"`` for content that is already compressed. Unset fields default
to an mtime of 1980-01-01T00:00:00Z, the earliest a zip header holds, and mode
``0o644``, which makes archives reproducible."""
data = text_encode(content) if isinstance(content, str) else content
return ContentEntry(_header(path, "File", method, mtime, mode, len(data)), data)file_stream#
file_stream[E = Never, R = Never](path: str, body: Stream[bytes, E, R], *, method: Literal['Deflate'] = ..., size: int | None = ..., mtime: datetime | None = ..., mode: int | None = ...) -> Entry[E, R]
file_stream[E = Never, R = Never](path: str, body: Stream[bytes, E, R], *, method: Literal['Store'], size: int, mtime: datetime | None = ..., mode: int | None = ...) -> Entry[E, R]A file streamed from body, which runs when the entry is encoded, with its
sizes and CRC-32 in a data descriptor after the data.
size is the exact byte length: required for "Store", since streaming
readers can only find the end of stored data from its size, and optional for
"Deflate", where it is checked against the body.
Non-empty stored entries are followed by a data descriptor, which some streaming
readers mishandle: Java's ZipInputStream rejects them, and libarchive reading
from a pipe can end them at bytes that look like a descriptor. Use "Deflate"
or an in-memory file for untrusted content and for those readers.
| Parameter | Type | Description |
|---|---|---|
path | ||
body | ||
method | = 'Deflate' | |
size | = None | |
mtime | = None | |
mode | = None |
@overload
def file_stream[E = Never, R = Never](
path: str,
body: Stream[bytes, E, R],
*,
method: Literal["Deflate"] = ...,
size: int | None = ...,
mtime: datetime | None = ...,
mode: int | None = ...,
) -> Entry[E, R]: ...
@overload
def file_stream[E = Never, R = Never](
path: str,
body: Stream[bytes, E, R],
*,
method: Literal["Store"],
size: int,
mtime: datetime | None = ...,
mode: int | None = ...,
) -> Entry[E, R]: ...
def file_stream(
path: str,
body: Stream[bytes, Any, Any],
*,
method: Method = "Deflate",
size: int | None = None,
mtime: datetime | None = None,
mode: int | None = None,
) -> Entry[Any, Any]:
"""A file streamed from ``body``, which runs when the entry is encoded, with its
sizes and CRC-32 in a data descriptor after the data.
``size`` is the exact byte length: required for ``"Store"``, since streaming
readers can only find the end of stored data from its size, and optional for
``"Deflate"``, where it is checked against the body.
Non-empty stored entries are followed by a data descriptor, which some streaming
readers mishandle: Java's ``ZipInputStream`` rejects them, and libarchive reading
from a pipe can end them at bytes that look like a descriptor. Use ``"Deflate"``
or an in-memory ``file`` for untrusted content and for those readers."""
require_stream(body, "body")
return Entry(_header(path, "File", method, mtime, mode, size), body)directory#
directory(path, *, mtime=None, mode=None) -> ContentEntryA directory (mode 0o755 by default). A trailing / is added to a
non-empty path; an empty one stays empty, so that encode rejects it.
| Parameter | Type | Description |
|---|---|---|
path | str | |
mtime | datetime | None = None | |
mode | int | None = None |
Returns ContentEntry
def directory(path: str, *, mtime: datetime | None = None, mode: int | None = None) -> ContentEntry:
"""A directory (mode ``0o755`` by default). A trailing ``/`` is added to a
non-empty ``path``; an empty one stays empty, so that ``encode`` rejects it."""
named = path if path == "" or path.endswith("/") else f"{path}/"
return ContentEntry(_header(named, "Directory", "Store", mtime, mode, 0), b"")decode#
decode[IE = Never, D = None]() -> Channel[tuple[Entry[ZipError | IE], ...], ZipError | IE, D, tuple[bytes, ...], IE, D]A channel decoding archive bytes into entries, one entry per output chunk. Each
body streams the uncompressed bytes and is checked against its CRC-32 and sizes;
pulling the next entry skips what is left of the current body. Reading stops at the
central directory, so mode, comments and entries only it lists are not reported.
Paths use the UTF-8 flag when set, otherwise the first Info-ZIP Unicode path field when it matches the name; other paths are UTF-8 when valid and CP437 otherwise. Times come from the extended timestamp when present, otherwise from the DOS fields, read as UTC.
Read each body before pulling the next entry and while the entry stream runs, for
example in map_effect: a later read fails with "BodyConsumed", so operators
that pull ahead cannot sit between decode and the reads. A body reads its bytes
once: running it again continues where it stopped. Every ZipError ends the
archive: later reads fail with the same error.
Archives that do not start with an entry or a central directory, such as
self-extracting ones, fail with "InvalidHeader". Stored entries whose sizes only
follow their data fail with "Unsupported": searching for their end would let an
entry's content forge the entries after it. A body growing past its size fails
with "SizeMismatch" before the extra bytes are written. Deflated data can expand
about a thousand times, and pulling the next entry inflates the rest of the current
body to find its end: for untrusted archives check size, count the bytes of
bodies without one, and end the stream at an entry that is too large rather than
skip it. Corrupt deflated data fails with "InvalidData" and the message of
Effect's inflater: zlib inflates, and an entry it rejects, or that ends early or
grows past its size, is replayed through a port of Effect's inflater. Only the
first 4 MiB of an entry's compressed input are kept for that: a corrupt entry
longer than that fails with Effect's kind and zlib's message. Paths with a NUL
character fail with "InvalidHeader". The channel ends only when its input ends:
input after the central directory is read and discarded, so that the upstream's
done value can be passed on.
Returns Channel[tuple[Entry[ZipError | IE], ...], ZipError | IE, D, tuple[bytes, ...], IE, D]
def decode[IE = Never, D = None]() -> Channel[
tuple[Entry[ZipError | IE], ...], ZipError | IE, D, tuple[bytes, ...], IE, D
]:
"""A channel decoding archive bytes into entries, one entry per output chunk. Each
body streams the uncompressed bytes and is checked against its CRC-32 and sizes;
pulling the next entry skips what is left of the current body. Reading stops at the
central directory, so ``mode``, comments and entries only it lists are not reported.
Paths use the UTF-8 flag when set, otherwise the first Info-ZIP Unicode path field
when it matches the name; other paths are UTF-8 when valid and CP437 otherwise.
Times come from the extended timestamp when present, otherwise from the DOS fields,
read as UTC.
Read each body before pulling the next entry and while the entry stream runs, for
example in ``map_effect``: a later read fails with ``"BodyConsumed"``, so operators
that pull ahead cannot sit between ``decode`` and the reads. A body reads its bytes
once: running it again continues where it stopped. Every ``ZipError`` ends the
archive: later reads fail with the same error.
Archives that do not start with an entry or a central directory, such as
self-extracting ones, fail with ``"InvalidHeader"``. Stored entries whose sizes only
follow their data fail with ``"Unsupported"``: searching for their end would let an
entry's content forge the entries after it. A body growing past its ``size`` fails
with ``"SizeMismatch"`` before the extra bytes are written. Deflated data can expand
about a thousand times, and pulling the next entry inflates the rest of the current
body to find its end: for untrusted archives check ``size``, count the bytes of
bodies without one, and end the stream at an entry that is too large rather than
skip it. Corrupt deflated data fails with ``"InvalidData"`` and the message of
Effect's inflater: ``zlib`` inflates, and an entry it rejects, or that ends early or
grows past its ``size``, is replayed through a port of Effect's inflater. Only the
first 4 MiB of an entry's compressed input are kept for that: a corrupt entry
longer than that fails with Effect's kind and ``zlib``'s message. Paths with a NUL
character fail with ``"InvalidHeader"``. The channel ends only when its input ends:
input after the central directory is read and discarded, so that the upstream's
done value can be passed on."""
return decode_channel(Decoder, Entry, ZipError)encode#
encode[E = Never, R = Never, IE = Never, D = None]() -> Channel[tuple[bytes, ...], ZipError | IE | E, D, tuple[Entry[E, R] | ContentEntry, ...], IE, D, R]A channel encoding entries into archive bytes. Each entry is written as soon as
it arrives: a local header, the stored or deflated body and, for a streamed body, a
data descriptor. The central directory is written once the input ends. Paths are
UTF-8, with the UTF-8 flag when they are not ASCII. mtime is written both as a
DOS time in UTC (two-second resolution, 1980 to 2107) and, between 1970 and 2038, as
an extended timestamp. ZIP64 fields are added when a size, offset or the entry count
needs them, and to the local header of a deflated entry streamed without a size
or with one near 4 GiB.
Output is written in chunks of about 64 KiB, and large body chunks pass through
uncopied. A "Deflate" body with a size of at most 64 KiB is collected and
compressed in one piece; omit size to stream it.
A compressor failure is a defect. Deflated bytes come from zlib, so they can
differ from another implementation's; archives of stored entries are byte-identical
to Effect's.
A body whose byte count differs from a set size, or any bytes for a directory,
fail with "SizeMismatch". Empty paths, paths starting with / or a drive
letter such as C:, paths containing \\ or NUL, File paths ending with
/, Directory paths not ending with /, invalid modes or sizes and naive
datetime values fail with "InvalidHeader". Other paths are written as given,
including .. segments, so validate untrusted paths before encoding them.
Entries that differ in their bodies' errors or services do not infer one E and
R: annotate the stream, as Stream[Entry[E1 | E2, R1 | R2] | ContentEntry].
Returns Channel[tuple[bytes, ...], ZipError | IE | E, D, tuple[Entry[E, R] | ContentEntry, ...], IE, D, R]
def encode[E = Never, R = Never, IE = Never, D = None]() -> Channel[
tuple[bytes, ...],
ZipError | IE | E,
D,
tuple[Entry[E, R] | ContentEntry, ...],
IE,
D,
R,
]:
"""A channel encoding entries into archive bytes. Each entry is written as soon as
it arrives: a local header, the stored or deflated body and, for a streamed body, a
data descriptor. The central directory is written once the input ends. Paths are
UTF-8, with the UTF-8 flag when they are not ASCII. ``mtime`` is written both as a
DOS time in UTC (two-second resolution, 1980 to 2107) and, between 1970 and 2038, as
an extended timestamp. ZIP64 fields are added when a size, offset or the entry count
needs them, and to the local header of a deflated entry streamed without a ``size``
or with one near 4 GiB.
Output is written in chunks of about 64 KiB, and large body chunks pass through
uncopied. A ``"Deflate"`` body with a ``size`` of at most 64 KiB is collected and
compressed in one piece; omit ``size`` to stream it.
A compressor failure is a defect. Deflated bytes come from ``zlib``, so they can
differ from another implementation's; archives of stored entries are byte-identical
to Effect's.
A body whose byte count differs from a set ``size``, or any bytes for a directory,
fail with ``"SizeMismatch"``. Empty paths, paths starting with ``/`` or a drive
letter such as ``C:``, paths containing ``\\\\`` or NUL, ``File`` paths ending with
``/``, ``Directory`` paths not ending with ``/``, invalid modes or sizes and naive
``datetime`` values fail with ``"InvalidHeader"``. Other paths are written as given,
including ``..`` segments, so validate untrusted paths before encoding them.
Entries that differ in their bodies' errors or services do not infer one ``E`` and
``R``: annotate the stream, as ``Stream[Entry[E1 | E2, R1 | R2] | ContentEntry]``."""
channel: Any = from_transform(
lambda upstream, scope: _Suspend(
lambda: _Succeed(_Suspend(_ZipEncoding(upstream, scope).step))
)
)
return channel