zip(3)

πŸ“¦
version 29.0.6 Β· 3 versions
, in ubuntu stonking

NAME πŸŽ€

okay bestie, meet zip β€” a whole entire utility for reading and creating 'zip' archives ✨ this is the zip(3) page from the Erlang Module Definition, and yes we are doing this πŸ’–


DESCRIPTION πŸ¦‹

So like, this module archives and extracts files to and from a zip archive. The zip format itself is specified by the "ZIP Appnote.txt" file, which lives on the PKWARE web site www.pkware.com (iykyk).

The zip module supports zip archive versions up to 6.1. However β€” password-protection is not supported. Not even a little bit. πŸ’€

By convention, the name of a zip file is to end with .zip. To abide to the convention, add .zip to the filename. That's it, that's the convention, she's simple like that.

  • To create zip archives, use function zip/2 or zip/3. They are also available as create/2,3, to resemble the erl_tar module.
  • To extract files from a zip archive, use function unzip/1 or unzip/2. They are also available as extract/1,2, to resemble the erl_tar module.
  • To fold a function over all files in a zip archive, use function foldl/3.
  • To return a list of the files in a zip archive, use function list_dir/1 or list_dir/2. They are also available as table/1,2, to resemble the erl_tar module.
  • To print a list of files to the Erlang shell, use function t/1 or tt/1.
  • Sometimes it is desirable to open a zip archive, and to unzip files from it file by file, without having to reopen the archive. This can be done by functions zip_open/1,2, zip_get/1,2, zip_list_dir/1, and zip_close/1. So efficient of her honestly πŸ‘‘
  • The ZIP extensions 0x5355 "extended timestamps" and 0x7875 "UID+GID handling" are supported. Both extensions are by default enabled when creating an archive, but only "extended timestamps" are enabled when extracting. Use the extra/0 option to change how these extensions are used. Options bestie, we love options πŸ’…

Limitations 😭

These are the "she does NOT do that" list, and they are real, so don't come for me when they bite you.
  • Password-protected and encrypted archives are not supported. Full stop. No cap.
  • Only the DEFLATE (zlib-compression) and the STORE (uncompressed data) zip methods are supported. Those two. Nobody else showed up to the party.
  • Comments for individual files are not supported when creating zip archives. The zip archive comment for the whole zip archive is supported tho, so you get one comment and it's the big one πŸŽ€
  • Changing a zip archive is not supported. To add or remove a file from an archive, the whole archive must be recreated. Annoying? yes. Optional? no. πŸ™ˆ

DATA TYPES 🧚

create_option()

create_option() ::
          memory | cooked | verbose |
          {comment, Comment :: string()} |
          {cwd, CWD :: file:filename()} |
          {compress, What :: extension_spec()} |
          {uncompress, What :: extension_spec()} |
          {extra, extra()}.

These options are described in create/3. (Go look, they're all over there.)

extension()

extension() :: string().

A filename extension, for example ".txt".

extension_spec()

extension_spec() ::
          all |
          [Extension :: extension()] |
          {add, [Extension :: extension()]} |
          {del, [Extension :: extension()]}.

extra()

extra() :: [extended_timestamp | uid_gid].

The possible extra extension that can be used. There are exactly two and they are:

  • extended_timestamp β€” enables the 0x5455 "extended timestamps" zip extension that embeds POSIX timestamps for access and modification times for each file in the archive. This makes the timestamps to be in UTC instead of local time and also increases the time resolution from 2 seconds to 1 second. Tiny but mighty ⏱️
  • uid_gid β€” enables 0x7875 "UNIX 3rd generation" zip extension that embeds the UID and GID for each file into the archive.

filename()

filename() :: file:filename().

The name of a zip file.

handle()

-opaque handle()

As returned by zip_open/2.

zip_comment()

zip_comment() :: #zip_comment{}.

The record zip_comment only contains the archive comment for a zip archive. That's the whole record, she's little but she's doing her best 🫢

zip_file()

zip_file() :: #zip_file{}.

The record zip_file contains the following fields:

  • name β€” The filename.
  • info β€” File information as in file:read_file_info/1 in Kernel. mtime, atime and ctime are expected to be in local time if represented using calendar:datetime/0, or in OS system time if represented by an integer. Keep track of which one you're using, bestie, do not mix them 😭
  • comment β€” The comment for the file in the zip archive.
  • offset β€” The file offset in the zip archive (used internally). Don't touch, she's internal.
  • comp_size β€” The size of the compressed file (the size of the uncompressed file is found in info). Yes, the other number is over in info, go get it there.

FUNCTIONS πŸ”₯

foldl(Fun, Acc0, Archive) -> {ok, Acc1} | {error, Reason}

foldl(Fun, Acc0, Archive) -> {ok, Acc1} | {error, Reason}
                when
                    Fun ::
                        fun((FileInArchive, GetInfo, GetBin, AccIn) ->
                                AccOut),
                    FileInArchive :: file:name(),
                    GetInfo :: fun(() -> file:file_info()),
                    GetBin :: fun(() -> binary()),
                    Acc0 :: term(),
                    Acc1 :: term(),
                    AccIn :: term(),
                    AccOut :: term(),
                    Archive :: file:name() | {file:name(), binary()},
                    Reason :: term().

Calls Fun(FileInArchive, GetInfo, GetBin, AccIn) on successive files in the Archive, starting with AccIn == Acc0. It just keeps going down the list, one file at a time, main character energy πŸ‘‘

FileInArchive is the name that the file has in the archive.

GetInfo is a fun that returns information about the file.

GetBin returns the file contents.

Both GetInfo and GetBin must be called within the Fun. Their behavior is undefined if they are called outside the context of Fun. Undefined behaviour, bestie. Do not test it. Do not be curious.

The Fun must return a new accumulator, which is passed to the next call. foldl/3 returns the final accumulator value. Acc0 is returned if the archive is empty. It is not necessary to iterate over all files in the archive. The iteration can be ended prematurely in a controlled manner by throwing an exception. So dramatic and so legal ✨

Example:

> Name = "dummy.zip".
"dummy.zip"
> {ok, {Name, Bin}} = zip:create(Name, [{"foo", <<"FOO">>}, {"bar", <<"BAR">>}], [memory]).
{ok,{"dummy.zip",
     <<80,75,3,4,20,0,0,0,0,0,74,152,97,60,171,39,212,26,3,0,
       0,0,3,0,0,...>>}}
> {ok, FileSpec} = zip:foldl(fun(N, I, B, Acc) -> [{N, B(), I()} | Acc] end, [], {Name, Bin}).
{ok,[{"bar",<<"BAR">>,
      {file_info,3,regular,read_write,
                 {{2010,3,1},{19,2,10}},
                 {{2010,3,1},{19,2,10}},
                 {{2010,3,1},{19,2,10}},
                 54,1,0,0,0,0,0}},
     {"foo",<<"FOO">>,
      {file_info,3,regular,read_write,
                 {{2010,3,1},{19,2,10}},
                 {{2010,3,1},{19,2,10}},
                 {{2010,3,1},{19,2,10}},
                 54,1,0,0,0,0,0}}]}
> {ok, {Name, Bin}} = zip:create(Name, lists:reverse(FileSpec), [memory]).
{ok,{"dummy.zip",
     <<80,75,3,4,20,0,0,0,0,0,74,152,97,60,171,39,212,26,3,0,
       0,0,3,0,0,...>>}}
> catch zip:foldl(fun("foo", _, B, _) -> throw(B()); (_,_,_,Acc) -> Acc end, [], {Name, Bin}).
<<"FOO">>

list_dir(Archive, Options) -> RetValue

list_dir(Archive, Options) -> RetValue
                  when
                      Archive :: file:name() | binary(),
                      RetValue ::
                          {ok, CommentAndFiles} |
                          {error, Reason :: term()},
                      CommentAndFiles :: [zip_comment() | zip_file()],
                      Options :: [Option],
                      Option ::
                          cooked | skip_directories | {extra, extra()}.

Retrieves all filenames in the zip archive Archive. Give her an archive, she gives you the names. Slay.

The result value is the tuple {ok, List}, where List contains the zip archive comment as the first element. (First!! Don't skip past it thinking it's a file, it's the comment πŸŽ€)

One option is available:

  • cooked β€” By default, this function opens the zip file in raw mode, which is faster but does not allow a remote (Erlang) file server to be used. Adding cooked to the mode list overrides the default and opens the zip file without option raw.
  • skip_directories β€” By default empty directories within zip archives are listed. With option skip_directories set, empty directories are no longer listed. Bye empty dirs, we won't miss you πŸ’…
  • {extra, Extras} β€” The zip "extra" features to respect. The supported "extra" features are "extended timestamps" and "UID and GID" handling. By default only "extended timestamps" is enabled when listing files. See extra/0 for more details.

t(Archive) -> ok

t(Archive) -> ok
              when
                  Archive :: file:name() | binary() | ZipHandle,
                  ZipHandle :: handle().

Prints all filenames in the zip archive Archive to the Erlang shell. (Similar to tar t.) Just the names, no lore πŸ¦‹


tt(Archive) -> ok

tt(Archive) -> ok
               when
                   Archive :: file:name() | binary() | ZipHandle,
                   ZipHandle :: handle().

Prints filenames and information about all files in the zip archive Archive to the Erlang shell. (Similar to tar tv.) Extra t, extra tea β˜•


unzip(Archive, Options) -> RetValue

unzip(Archive, Options) -> RetValue
               when
                   Archive :: file:name() | binary(),
                   Options :: [Option],
                   Option ::
                       {file_list, FileList} |
                       cooked | keep_old_files | verbose | memory |
                       skip_directories |
                       {file_filter, FileFilter} |
                       {cwd, CWD} |
                       {extra, extra()},
                   FileList :: [file:name()],
                   FileBinList :: [{file:name(), binary()}],
                   FileFilter :: fun((ZipFile) -> boolean()),
                   CWD :: file:filename(),
                   ZipFile :: zip_file(),
                   RetValue ::
                       {ok, FileList} |
                       {ok, FileBinList} |
                       {error, Reason :: term()} |
                       {error, {Name :: file:name(), Reason :: term()}}.

Extracts all files from a zip archive. All of them. The whole archive. She is not shy ✨

If argument Archive is specified as a binary/0, the contents of the binary is assumed to be a zip archive, otherwise a filename. So you can hand her a name or hand her the actual bytes, her call πŸ’–

Options:

okay so you're still deep in unzip/2 territory and these are its options β€” every single one, no skipping, we're finishing the set πŸ’…

πŸŽ€ the unzip/2 options

  • {file_list, FileList} β€” by default every file gets pulled out of the zip archive. With this option, unzip/2 only extracts the files whose names are inside FileList. And bestie, listen β€” you have to give the full paths, including the names of all the subdirectories inside the zip archive. No shortcuts, okay? 🫢
  • cooked β€” by default this function opens the zip file in raw mode, which is faster but does not let you use a remote (Erlang) file server. Adding cooked to the mode list overrides that default and opens the zip file without the raw option. The same thing applies for the files that get extracted. ✨
  • keep_old_files β€” by default, all files with the same name as files in the zip archive get overwritten πŸ™ˆ. With keep_old_files set, unzip/2 does not overwrite existing files. And heads up: even with memory specified β€” which means no files get overwritten anyway β€” existing files are excluded from the result. Just so you know.
  • skip_directories β€” by default, empty directories inside zip archives do get extracted. With skip_directories set, those empty directories are no longer created. slay for clean output 🌸
  • {extra, Extras} β€” the zip "extra" features you want respected. The supported ones are "extended timestamps" and "UID and GID" handling. By default only "extended timestamps" is enabled when unzipping. See extra/0 for the deets. πŸ‘‘
  • verbose β€” prints an informational message for each extracted file. chatty and honestly iconic.
  • memory β€” instead of extracting to the current directory, the result comes back as a list of tuples {Filename, Binary}, where Binary is a binary containing the extracted data of the file Filename in the zip archive. no disk writes, just vibes ✨
  • {cwd, CWD} β€” uses the specified directory as the current directory. It gets prepended to filenames when extracting them from the zip archive. (Acting like file:set_cwd/1 in Kernel, but without changing the global cwd property. so polite 🫢)

🌈 zip(Name, FileList, Options) -> RetValue

zip(Name, FileList, Options) -> RetValue
     when
         Name :: file:name(),
         FileList :: [FileSpec],
         FileSpec ::
             file:name() |
             {file:name(), binary()} |
             {file:name(), binary(), file:file_info()},
         Options :: [Option],
         Option :: create_option(),
         RetValue ::
             {ok, FileName :: file:name()} |
             {ok, {FileName :: file:name(), binary()}} |
             {error, Reason :: term()}.

Creates a zip archive containing the files specified in FileList. πŸ’–

FileList is a list of files, with paths relative to the current directory, and those files are stored with this path in the archive. File system operations are performed to read the file metadata and, when compression is enabled, to stream the file contents without loading whole files into memory. Files can also be specified as binaries, which creates an archive directly from data β€” and in those cases, no metadata or file system reads happen at all. main character energy fr fr.

Files are compressed using the DEFLATE compression, as described in the "Appnote.txt" file. However, files are stored without compression if they're already compressed. zip/2 and zip/3 check the file extension to figure out whether the file should be stored without compression. Files with the following extensions are not compressed: .Z, .zip, .zoo, .arc, .lzh, .arj. πŸ¦‹

It is possible to override the default behavior and control what types of files get compressed by using the options {compress, What} and {uncompress, What}. You can also use many compress and uncompress options. πŸ™Œ

To trigger file compression, its extension must match the compress condition and must not match the uncompress condition. For example, if compress is set to ["gif", "jpg"] and uncompress is set to ["jpg"], only files with extension "gif" are compressed. iykyk ✨

πŸ’… options

  • cooked β€” by default this function opens the zip file in mode raw, which is faster but does not allow a remote (Erlang) file server to be used. Adding cooked to the mode list overrides the default and opens the zip file without the raw option. The same applies for the files being added. πŸ‘‘
  • verbose β€” prints an informational message about each added file.
  • memory β€” the output isn't written to a file, but comes back instead as a tuple {FileName, binary()}. That binary is a full zip archive with header, and it can be extracted with, for example, unzip/2. πŸŽ€
  • {comment, Comment} β€” adds a comment to the zip archive.
  • {cwd, CWD} β€” uses the specified directory as current work directory (cwd). This is prepended to filenames when adding them, although not in the zip archive (acting like file:set_cwd/1 in Kernel, but without changing the global cwd property.). so considerate 🫢
  • {extra, Extras} β€” the zip "extra" features to respect. The supported "extra" features are "extended timestamps" and "UID and GID" handling. By default both these "extra" features are enabled. See extra/0 for more details. ⭐
  • {compress, What} β€” controls what types of files get compressed. Defaults to all. The following values of What are allowed:
    • all All files are compressed (as long as they pass the uncompress condition).
    • [Extension] Only files with exactly these extensions are compressed.
    • {add,[Extension]} Adds these extensions to the list of compress extensions.
    • {del,[Extension]} Deletes these extensions from the list of compress extensions.
  • {uncompress, What} β€” controls what types of files get uncompressed. Defaults to [".Z", ".zip", ".zoo", ".arc", ".lzh", ".arj"]. The following values of What are allowed:
    • all No files are compressed. (yes bestie, that is literally what it says β€” read it twice, it's giving paradox πŸ’€)
    • [Extension] Files with these extensions are uncompressed.
    • {add,[Extension]} Adds these extensions to the list of uncompress extensions.
    • {del,[Extension]} Deletes these extensions from the list of uncompress extensions.

πŸ¦‹ zip_close(ZipHandle) -> ok | {error, einval}

zip_close(ZipHandle) -> ok | {error, einval}
                   when ZipHandle :: handle().

Closes a zip archive that was previously opened with zip_open/1,2. All resources are closed, and the handle is not to be used after closing. periodt. 🚫


✨ zip_get(FileName, ZipHandle) -> {ok, Result} | {error, Reason}

zip_get(FileName, ZipHandle) -> {ok, Result} | {error, Reason}
                  when
                      FileName :: file:name(),
                      ZipHandle :: handle(),
                      Result :: file:name() | {file:name(), binary()},
                      Reason :: term().

Extracts one or all files from an open archive. πŸ’–

The files are unzipped to memory or to file, depending on the options you specified to the function zip_open/1,2 when you opened the archive.


🌸 zip_get_crc32(FileName, ZipHandle) -> {ok, CRC} | {error, Reason}

zip_get_crc32(FileName, ZipHandle) -> {ok, CRC} | {error, Reason}
                            when
                                FileName :: file:name(),
                                ZipHandle :: handle(),
                                CRC :: non_neg_integer(),
                                Reason :: term().

Extracts one crc32 checksum from an open archive. one singular checksum, we love a specialist ✨


πŸ‘‘ zip_list_dir(ZipHandle) -> {ok, Result} | {error, Reason}

zip_list_dir(ZipHandle) -> {ok, Result} | {error, Reason}
                       when
                           Result :: [zip_comment() | zip_file()],
                           ZipHandle :: handle(),
                           Reason :: term().

Returns the file list of an open zip archive. And plot twist β€” the first element that comes back is the zip archive comment. πŸ™ˆ


πŸ’œ zip_open(Archive, Options) -> {ok, ZipHandle} | {error, Reason}

zip_open(Archive, Options) -> {ok, ZipHandle} | {error, Reason}
                   when
                       Archive :: file:name() | binary(),
                       ZipHandle :: handle(),
                       Options :: [Option],
                       Option ::
                           cooked | memory |
                           {cwd, CWD :: file:filename()} |
                           {extra, extra()},
                       Reason :: term().

Opens a zip archive, and reads and saves its directory. Which means that reading files from the archive later is faster than unzipping files one at a time with unzip/1,2. glow-up via caching, we love to see it πŸ’…

The options are equivalent to those in unzip/2. πŸ‘―

The archive must be closed with zip_close/1. don't leave it hanging bestie 😭

The ZipHandle is closed if the process that originally opened the archive dies. rip to that process, but the handle is freed πŸ•ŠοΈ


and that's the whole page, no crumbs left 🌈🧚 before you go: this beauty is brought to you by Ericsson AB, it's from stdlib 8.0.4, and it's your girl zip(3) β€” go forth and archive responsibly, mwah πŸ’–πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from