-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathzip.erl
2748 lines (2449 loc) · 96.2 KB
/
zip.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2006-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(zip).
-moduledoc """
Utility for reading and creating 'zip' archives.
This module archives and extracts files to and from a zip archive. The zip
format is specified by the "ZIP Appnote.txt" file, available on the PKWARE web
site [www.pkware.com](http://www.pkware.com).
The zip module supports zip archive versions up to 6.1. However,
password-protection is not supported.
By convention, the name of a zip file is to end with `.zip`. To abide to the
convention, add `.zip` to the filename.
- To create zip archives, use function `zip/2` or `zip/3`. They are
also available as [`create/2,3`](`create/3`), to resemble the `m: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`](`extract/1`), to resemble the `m: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`](`table/1`), to resemble the
`m: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_open/1`), [`zip_get/1,2`](`zip_get/1`),
`zip_list_dir/1`, and `zip_close/1`.
- 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 `t:extra/0`
option to change how these extensions are used.
## Limitations
- Password-protected and encrypted archives are not supported.
- Only the DEFLATE (zlib-compression) and the STORE (uncompressed data) zip
methods are supported.
- Comments for individual files are not supported when creating zip archives.
The zip archive comment for the whole zip archive is supported.
- Changing a zip archive is not supported. To add or remove a file from an
archive, the whole archive must be recreated.
""".
-define(ERL_TAR_COMPATIBILITY, ~"erl_tar compatibility functions").
-moduledoc(#{ titles => [{function, ?ERL_TAR_COMPATIBILITY}]}).
%% Basic api
-export([unzip/1, unzip/2, extract/1, extract/2,
zip/2, zip/3, create/2, create/3, foldl/3,
list_dir/1, list_dir/2, table/1, table/2,
t/1, tt/1]).
%% zip server
-export([zip_open/1, zip_open/2,
zip_get/1, zip_get/2, zip_get_crc32/2,
zip_list_dir/1, zip_close/1]).
%% includes
-include("file.hrl"). % #file_info
-include("zip.hrl"). % #zip_file, #zip_comment
%% max bytes fed to zlib
-define(WRITE_BLOCK_SIZE, 8*1024).
%% for debugging, to turn off catch
-define(CATCH(Expr), (catch (Expr))).
%% option sets
-record(unzip_opts, {
output, % output object (fun)
input, % input object (fun)
file_filter, % file filter (boolean fun)
open_opts, % options passed to file:open
feedback, % feeback (fun)
cwd, % directory to relate paths to
skip_dirs, % skip creating empty directories
extra % The extra fields to include
}).
-record(zip_opts, {
output, % output object (fun)
input, % input object (fun)
comment, % zip-file comment
open_opts, % options passed to file:open
feedback, % feeback (fun)
cwd, % directory to relate paths to
compress, % compress files with these suffixes
uncompress, % uncompress files with these suffixes
extra % The extra fields to include
}).
-record(list_dir_opts, {
input, % input object (fun)
raw_iterator,% applied to each dir entry
open_opts, % options passed to file:open
skip_dirs, % skip creating empty directories
extra % The extra fields to include
}).
-record(openzip_opts, {
output, % output object (fun)
open_opts, % file:open options
cwd, % directory to relate paths to
skip_dirs, % skip creating empty directories
extra % The extra fields to include
}).
% openzip record, state for an open zip-file
-record(openzip, {
zip_comment, % zip archive comment
files, % filenames, infos, comments and offsets
in, % archive handle
input, % archive io object (fun)
output, % output io object (fun)
zlib, % handle to open zlib
cwd, % directory to relate paths to
skip_dirs, % skip creating empty directories
extra % The extra fields to include
}).
% Things that I would like to add to the public record #zip_file,
% but can't as it would make things fail at upgrade.
% Instead we use {#zip_file,#zip_file_extra} internally.
-record(zip_file_extra, {
crc32 % checksum
}).
%% max bytes read from files and archives (and fed to zlib)
-define(READ_BLOCK_SIZE, 16*1024).
%% ZIP-file format records and defines
%% compression methods
-define(STORED, 0).
-define(UNCOMPRESSED, 0).
-define(SHRUNK, 1).
-define(REDUCED_1, 2).
-define(REDUCED_2, 3).
-define(REDUCED_3, 4).
-define(REDUCED_4, 5).
-define(IMPLODED, 6).
-define(TOKENIZED, 7).
-define(DEFLATED, 8).
-define(DEFLATED_64, 9).
-define(PKWARE_IMPLODED, 10).
-define(PKWARE_RESERVED, 11).
-define(BZIP2_COMPRESSED, 12).
%% Version 2.6, attribute compatibility type 3 (Unix)
-define(OS_MADE_BY_UNIX, 3).
-define(VERSION_NEEDED_STORE, 10).
-define(VERSION_NEEDED_DEFLATE, 20).
-define(VERSION_NEEDED_ZIP64, 45).
-define(VERSION_MADE_BY, 61).
-define(GP_BIT_11, 16#800). % Filename and file comment UTF-8 encoded.
%% zip-file records
-define(LOCAL_FILE_MAGIC,16#04034b50).
-define(LOCAL_FILE_HEADER_SZ,(4+2+2+2+2+2+4+4+4+2+2)).
-define(LOCAL_FILE_HEADER_CRC32_OFFSET, 4+2+2+2+2+2).
-record(local_file_header,
{
%% Common with cd_file_header
version_needed,
gp_flag,
comp_method,
last_mod_time,
last_mod_date,
crc32,
comp_size,
uncomp_size,
%% X5455_EXTENDED_TIMESTAMP extension
mtime,
atime,
ctime,
%% X7875_UNIX3 extension
uid = 0,
gid = 0,
%% local_file_header specific
file_name_length,
extra_field_length,
%% extra data needed to create cd_file_header
info :: undefined | file:file_info()
}).
-define(EXTRA_OPTIONS, [extended_timestamp, uid_gid]).
-define(X0001_ZIP64, 16#0001).
-define(X5455_EXTENDED_TIMESTAMP, 16#5455).
-define(X7875_UNIX3, 16#7875).
-define(CENTRAL_FILE_HEADER_SZ,(4+2+2+2+2+2+2+4+4+4+2+2+2+2+2+4+4)).
-define(CENTRAL_DIR_MAGIC, 16#06054b50).
-define(CENTRAL_DIR_SZ, (4+2+2+2+2+4+4+2)).
-define(CENTRAL_DIR_DIGITAL_SIG_MAGIC, 16#05054b50).
-define(CENTRAL_DIR_DIGITAL_SIG_SZ, (4+2)).
-define(CENTRAL_FILE_MAGIC, 16#02014b50).
-define(DEFAULT_REGULAR_FILE_MODE, 8#644).
-define(DEFAULT_DIRECTORY_FILE_MODE, 8#744).
-record(cd_file_header,
{
%% Common with local_file_header
version_needed,
gp_flag,
comp_method,
last_mod_time,
last_mod_date,
crc32,
comp_size,
uncomp_size,
%% X5455_EXTENDED_TIMESTAMP extension
mtime,
atime,
ctime,
%% X7875_UNIX3 extension
uid = 0,
gid = 0,
%% cd_file_header specific
version_made_by,
os_made_by,
file_name_length,
extra_field_length,
file_comment_length,
disk_num_start,
internal_attr,
external_attr,
local_header_offset
}).
-define(END_OF_CENTRAL_DIR_64_LOCATOR_MAGIC, 16#07064b50).
-define(END_OF_CENTRAL_DIR_64_LOCATOR_SZ, (4+8+4)).
-define(END_OF_CENTRAL_DIR_64_MAGIC, 16#06064b50).
-define(END_OF_CENTRAL_DIR_64_SZ, (2+2+4+4+8+8+8+8)).
-define(END_OF_CENTRAL_DIR_MAGIC, 16#06054b50).
-define(END_OF_CENTRAL_DIR_SZ, (4+2+2+2+2+4+4+2)).
-define(MAX_INT32, 16#FFFF_FFFF).
-define(MAX_INT16, 16#FFFF).
%% 1.0 default version
%% 2.0 Deflate version
%% 4.5 File used ZIP64 format extension
%% 6.1 Version made by
-type zip_versions() :: 10 | 20 | 45 | 61.
-record(eocd, {eocd :: undefined | #eocd{},
version_made_by = 10 :: zip_versions(),
os_made_by = ~"UNIX" :: unicode:chardata() | 0..255,
extract_version = 10 :: zip_versions(),
disk_num,
start_disk_num,
entries_on_disk,
entries,
size,
offset,
zip_comment_length,
extra}).
-doc """
The possible extra extension that can be used.
- **`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.
- **`uid_gid`** - enables 0x7875 "UNIX 3rd generation" zip extension that embeds the
UID and GID for each file into the archive.
""".
-type extra() :: [extended_timestamp | uid_gid].
-doc "These options are described in [`create/3`](`m:zip#zip_options`).".
-type create_option() :: memory | cooked | verbose
| {comment, Comment ::string()}
| {cwd, CWD :: file:filename()}
| {compress, What :: extension_spec()}
| {uncompress, What :: extension_spec()}
| {extra, extra()}.
-doc ~'A filename extension, for example ".txt".'.
-type extension() :: string().
-type extension_spec() :: all
| [Extension :: extension()]
| {add, [Extension :: extension()]}
| {del, [Extension :: extension()]}.
-doc "The name of a zip file.".
-type filename() :: file:filename().
-doc "The record `zip_comment` only contains the archive comment for a zip archive.".
-type zip_comment() :: #zip_comment{}.
-doc """
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`](`erlang:localtime/0`) if represented using `t:calendar:datetime/0`,
or in [OS system time](`e:erts:time_correction.md#os-system-time`) if represented by an integer.
- **`comment`** - The comment for the file in the zip archive
- **`offset`** - The file offset in the zip archive (used internally)
- **`comp_size`** - The size of the compressed file (the size of the
uncompressed file is found in `info`)
""".
-type zip_file() :: #zip_file{}.
-doc "As returned by `zip_open/2`.".
-opaque handle() :: pid().
-export_type([create_option/0, filename/0, handle/0]).
%% Extract from a zip archive with options
%%
%% Accepted options:
%% verbose, cooked, file_list, keep_old_files, file_filter, memory
-doc(#{equiv => unzip(Archive, [])}).
-spec(unzip(Archive) -> RetValue when
Archive :: file:name() | binary(),
RetValue :: {ok, FileList}
| {ok, FileBinList}
| {error, Reason :: term()}
| {error, {Name :: file:name(), Reason :: term()}},
FileList :: [file:name()],
FileBinList :: [{file:name(),binary()}]).
unzip(F) -> unzip(F, []).
-doc """
Extracts all files from a zip archive.
If argument `Archive` is specified as a `t:binary/0`, the contents of the binary is
assumed to be a zip archive, otherwise a filename.
Options:
- **`{file_list, FileList}`** - By default, all files are extracted from the zip
archive. With option `{file_list, FileList}`, function [`unzip/2`](`unzip/2`)
only extracts the files whose names are included in `FileList`. The full
paths, including the names of all subdirectories within the zip archive, must
be specified.
- **`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`. The same applies for the files extracted.
- **`keep_old_files`** - By default, all files with the same name as files in
the zip archive are overwritten. With option `keep_old_files` set, function
[`unzip/2`](`unzip/2`) does not overwrite existing files. Notice that even
with option `memory` specified, which means that no files are overwritten,
existing files are excluded from the result.
- **`skip_directories`** - By default empty directories within zip archives are
extracted. With option `skip_directories` set, empty directories are no longer
created.
- **`{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 unzipping.
See `t:extra/0` for more details.
- **`verbose`** - Prints an informational message for each extracted file.
- **`memory`** - Instead of extracting to the current directory, the result is
given as a list of tuples `{Filename, Binary}`, where `Binary` is a binary
containing the extracted data of file `Filename` in the zip archive.
- **`{cwd, CWD}`** - Uses the specified directory as current directory. It is
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.)
""".
-spec(unzip(Archive, Options) -> RetValue when
Archive :: file:name() | binary(),
Options :: [Option],
Option :: {file_list, FileList} | cooked
| keep_old_files | verbose | memory |
{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()}}).
unzip(F, Options) ->
case ?CATCH(do_unzip(F, Options)) of
{ok, R} -> {ok, R};
Error -> {error, Error}
end.
do_unzip(F, Options) ->
Opts = get_unzip_options(F, Options),
#unzip_opts{input = Input, open_opts = OpO,
extra = ExtraOpts} = Opts,
In0 = Input({open, F, OpO -- [write]}, []),
RawIterator = fun raw_file_info_etc/5,
{Info, In1} = get_central_dir(In0, RawIterator, Input, ExtraOpts),
%% get rid of zip-comment
Z = zlib:open(),
Files = try
get_z_files(Info, Z, In1, Opts, [])
after
zlib:close(Z),
Input(close, In1)
end,
{ok, Files}.
%% Iterate over all files in a zip archive
-doc """
Calls `Fun(FileInArchive, GetInfo, GetBin, AccIn)` on successive files in the
`Archive`, starting with `AccIn == Acc0`.
`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`.
The `Fun` must return a new accumulator, which is passed to the next call.
[`foldl/3`](`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.
_Example:_
```erlang
> 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">>
```
""".
-doc(#{since => <<"OTP R14B">>}).
-spec(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()).
foldl(Fun, Acc0, {_Filename, Binary}) ->
foldl(Fun, Acc0, Binary);
foldl(Fun, Acc0, Archive) when is_function(Fun, 4) ->
case zip_open(Archive,[memory]) of
{ok, Handle} ->
{ok, Files} = zip_list_dir(Handle),
Acc1 =
lists:foldl(
fun(#zip_comment{}, Acc) ->
Acc;
(#zip_file{ name = Name, info = Info }, Acc) ->
GetInfo = fun() -> Info end,
GetBin = case lists:last(Name) of
$/ -> fun() -> <<>> end;
_ ->
fun() ->
case zip_get(Name, Handle) of
{ok, {Name, Data}} -> Data;
{error, Error} -> throw({Name, Error})
end
end
end,
Fun(Name, GetInfo, GetBin, Acc)
end, Acc0, Files),
ok = zip_close(Handle),
{ok, Acc1};
{error, bad_eocd} ->
{error, "Not an archive file"};
{error, Reason} ->
{error, Reason}
end;
foldl(_,_, _) ->
{error, einval}.
%% Create zip archive name F from Files or binaries
%%
%% Accepted options:
%% verbose, cooked, memory, comment
-doc(#{equiv => zip(Name, FileList, [])}).
-spec(zip(Name, FileList) -> RetValue when
Name :: file:name(),
FileList :: [FileSpec],
FileSpec :: file:name() | {file:name(), binary()}
| {file:name(), binary(), file:file_info()},
RetValue :: {ok, FileName :: file:name()}
| {ok, {FileName :: file:name(), binary()}}
| {error, Reason :: term()}).
zip(F, Files) -> zip(F, Files, []).
-doc """
Creates a zip archive containing the files specified in `FileList`.
`FileList` is a list of files, with paths relative to the current directory,
which 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 to create an archive directly from data. In such cases, no
metadata or file system reads are performed.
Files are compressed using the DEFLATE compression, as described in the
"Appnote.txt" file. However, files are stored without compression if they are
already compressed. [`zip/2`](`zip/2`) and [`zip/3`](`zip/3`) check the file
extension to determine if the file is to 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
that are to be compressed by using options `{compress, What}` and
`{uncompress, What}`. It is also possible to use many `compress` and
`uncompress` options.
To trigger file compression, its extension must match with 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.
[](){: #zip_options }
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 added.
- **`verbose`** - Prints an informational message about each added file.
- **`memory`** - The output is not to a file, but instead as a tuple
`{FileName, binary()}`. The binary is a full zip archive with header and 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.).
- **`{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 `t:extra/0` for more details.
- **`{compress, What}`** - Controls what types of files to be 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 to be uncompressed.
Defaults to `[".Z", ".zip", ".zoo", ".arc", ".lzh", ".arj"]`. The following
values of `What` are allowed:
- **`all`** - No files are compressed.
- **`[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.
""".
-spec(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()}).
zip(F, Files, Options) ->
case ?CATCH(do_zip(F, Files, Options)) of
{ok, R} -> {ok, R};
Error -> {error, Error}
end.
do_zip(F, Files, Options) ->
Opts = get_zip_options(Files, Options),
#zip_opts{output = Output, open_opts = OpO} = Opts,
Out0 = Output({open, F, OpO}, []),
Z = zlib:open(),
try
{Out1, LHS, Pos} = put_z_files(Files, Z, Out0, 0, Opts, []),
zlib:close(Z),
Out2 = put_central_dir(LHS, Pos, Out1, Opts),
Out3 = Output({close, F}, Out2),
{ok, Out3}
catch
C:R:Stk ->
?CATCH(zlib:close(Z)),
Output({close, F}, Out0),
erlang:raise(C, R, Stk)
end.
%% List zip directory contents
%%
%% Accepted options:
%% cooked, file_filter, file_output (latter 2 undocumented)
-doc(#{equiv => list_dir(Archive, [])}).
-spec(list_dir(Archive) -> RetValue when
Archive :: file:name() | binary(),
RetValue :: {ok, CommentAndFiles} | {error, Reason :: term()},
CommentAndFiles :: [zip_comment() | zip_file()]).
list_dir(F) -> list_dir(F, []).
-doc """
Retrieves all filenames in the zip archive `Archive`.
The result value is the tuple `{ok, List}`, where `List` contains the zip
archive comment as the first element.
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.
- **`{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 `t:extra/0` for more details.
""".
-spec(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 | {extra, extra()}).
list_dir(F, Options) ->
case ?CATCH(do_list_dir(F, Options)) of
{ok, R} -> {ok, R};
Error -> {error, Error}
end.
do_list_dir(F, Options) ->
Opts = get_list_dir_options(F, Options),
#list_dir_opts{input = Input, open_opts = OpO,
raw_iterator = RawIterator,
skip_dirs = SkipDirs,
extra = ExtraOpts} = Opts,
In0 = Input({open, F, OpO}, []),
{Info, In1} = get_central_dir(In0, RawIterator, Input, ExtraOpts),
Input(close, In1),
if SkipDirs ->
{ok,
lists:filter(
fun(#zip_file{ name = Name }) ->
lists:last(Name) =/= $/;
(#zip_comment{}) ->
true
end, Info)};
true ->
{ok, Info}
end.
-doc(#{equiv => zip_open/2}).
-spec(zip_open(Archive) -> {ok, ZipHandle} | {error, Reason} when
Archive :: file:name() | binary(),
ZipHandle :: handle(),
Reason :: term()).
zip_open(Archive) -> zip_open(Archive, []).
-doc """
Opens a zip archive, and reads and saves its directory. This means that later
reading files from the archive is faster than unzipping files one at a time with
[`unzip/1,2`](`unzip/1`).
The options are equivalent to those in `unzip/2`.
The archive must be closed with `zip_close/1`.
The `ZipHandle` is closed if the process that originally opened the archive
dies.
""".
-spec(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()).
zip_open(Archive, Options) ->
Self = self(),
Pid = spawn_link(fun() -> server_init(Self) end),
request(Self, Pid, {open, Archive, Options}).
-doc(#{equiv => zip_get/2}).
-spec(zip_get(ZipHandle) -> {ok, [Result]} | {error, Reason} when
ZipHandle :: handle(),
Result :: file:name() | {file:name(), binary()},
Reason :: term()).
zip_get(Pid) when is_pid(Pid) ->
request(self(), Pid, get).
-doc """
Closes a zip archive, previously opened with [`zip_open/1,2`](`zip_open/1`). All
resources are closed, and the handle is not to be used after closing.
""".
-spec(zip_close(ZipHandle) -> ok | {error, einval} when
ZipHandle :: handle()).
zip_close(Pid) when is_pid(Pid) ->
request(self(), Pid, close).
-doc """
Extracts one or all files from an open archive.
The files are unzipped to memory or to file, depending on the options specified
to function [`zip_open/1,2`](`zip_open/1`) when opening the archive.
""".
-spec(zip_get(FileName, ZipHandle) -> {ok, Result} | {error, Reason} when
FileName :: file:name(),
ZipHandle :: handle(),
Result :: file:name() | {file:name(), binary()},
Reason :: term()).
zip_get(FileName, Pid) when is_pid(Pid) ->
request(self(), Pid, {get, FileName}).
-doc "Extracts one crc32 checksum from an open archive.".
-doc(#{since => <<"OTP 26.0">>}).
-spec(zip_get_crc32(FileName, ZipHandle) -> {ok, CRC} | {error, Reason} when
FileName :: file:name(),
ZipHandle :: handle(),
CRC :: non_neg_integer(),
Reason :: term()).
zip_get_crc32(FileName, Pid) when is_pid(Pid) ->
request(self(), Pid, {get_crc32, FileName}).
-doc """
Returns the file list of an open zip archive. The first returned element is the
zip archive comment.
""".
-spec(zip_list_dir(ZipHandle) -> {ok, Result} | {error, Reason} when
Result :: [zip_comment() | zip_file()],
ZipHandle :: handle(),
Reason :: term()).
zip_list_dir(Pid) when is_pid(Pid) ->
request(self(), Pid, list_dir).
request(Self, Pid, Req) ->
Pid ! {Self, Req},
receive
{Pid, R} -> R
end.
zip_t(Pid) when is_pid(Pid) ->
Openzip = request(self(), Pid, get_state),
openzip_t(Openzip).
zip_tt(Pid) when is_pid(Pid) ->
Openzip = request(self(), Pid, get_state),
openzip_tt(Openzip).
%% Print zip directory in short form
-doc """
Prints all filenames in the zip archive `Archive` to the Erlang shell. (Similar
to `tar t`.)
""".
-spec(t(Archive) -> ok when
Archive :: file:name() | binary() | ZipHandle,
ZipHandle :: handle()).
t(F) when is_pid(F) -> zip_t(F);
t(F) -> t(F, fun raw_short_print_info_etc/5).
t(F, RawPrint) ->
case ?CATCH(do_t(F, RawPrint)) of
ok -> ok;
Error -> {error, Error}
end.
do_t(F, RawPrint) ->
Input = get_input(F),
OpO = [raw],
In0 = Input({open, F, OpO}, []),
{_Info, In1} = get_central_dir(In0, RawPrint, Input, ?EXTRA_OPTIONS),
Input(close, In1),
ok.
%% Print zip directory in long form (like ls -l)
-doc """
Prints filenames and information about all files in the zip archive `Archive` to
the Erlang shell. (Similar to `tar tv`.)
""".
-spec(tt(Archive) -> ok when
Archive :: file:name() | binary() | ZipHandle,
ZipHandle :: handle()).
tt(F) when is_pid(F) -> zip_tt(F);
tt(F) -> t(F, fun raw_long_print_info_etc/5).
%% option utils
get_unzip_opt([], Opts) ->
Opts;
get_unzip_opt([verbose | Rest], Opts) ->
get_unzip_opt(Rest, Opts#unzip_opts{feedback = fun verbose_unzip/1});
get_unzip_opt([cooked | Rest], #unzip_opts{open_opts = OpO} = Opts) ->
get_unzip_opt(Rest, Opts#unzip_opts{open_opts = OpO -- [raw]});
get_unzip_opt([memory | Rest], Opts) ->
get_unzip_opt(Rest, Opts#unzip_opts{output = fun binary_io/2});
get_unzip_opt([{cwd, CWD} | Rest], Opts) ->
get_unzip_opt(Rest, Opts#unzip_opts{cwd = CWD});
get_unzip_opt([{file_filter, F} | Rest], Opts) ->
Filter1 = fun({ZipFile,_Extra}) -> F(ZipFile) end,
Filter2 = fun_and_1(Filter1, Opts#unzip_opts.file_filter),
get_unzip_opt(Rest, Opts#unzip_opts{file_filter = Filter2});
get_unzip_opt([{file_list, L} | Rest], Opts) ->
FileInList = fun(F) -> file_in_list(F, L) end,
Filter = fun_and_1(FileInList, Opts#unzip_opts.file_filter),
get_unzip_opt(Rest, Opts#unzip_opts{file_filter = Filter});
get_unzip_opt([keep_old_files | Rest], Opts) ->
Keep = fun keep_old_file/1,
Filter = fun_and_1(Keep, Opts#unzip_opts.file_filter),
get_unzip_opt(Rest, Opts#unzip_opts{file_filter = Filter});
get_unzip_opt([skip_directories | Rest], Opts) ->
get_unzip_opt(Rest, Opts#unzip_opts{skip_dirs = true});
get_unzip_opt([{extra, What} = O| Rest], Opts) when is_list(What) ->
case lists:all(fun(E) -> lists:member(E, ?EXTRA_OPTIONS) end, What) of
true ->
get_zip_opt(Rest, Opts#unzip_opts{extra = What});
false ->
throw({bad_option, O})
end;
get_unzip_opt([Unknown | _Rest], _Opts) ->
throw({bad_option, Unknown}).
get_list_dir_opt([], Opts) ->
Opts;
get_list_dir_opt([cooked | Rest], #list_dir_opts{open_opts = OpO} = Opts) ->
get_list_dir_opt(Rest, Opts#list_dir_opts{open_opts = OpO -- [raw]});
get_list_dir_opt([names_only | Rest], Opts) ->
get_list_dir_opt(Rest, Opts#list_dir_opts{
raw_iterator = fun(A, B, C, D, E) -> raw_name_only(A, B, C, D, E) end});
get_list_dir_opt([skip_directories | Rest], Opts) ->
get_list_dir_opt(Rest, Opts#list_dir_opts{skip_dirs = true});
get_list_dir_opt([{extra, What} = O| Rest], Opts) when is_list(What) ->
case lists:all(fun(E) -> lists:member(E, ?EXTRA_OPTIONS) end, What) of
true ->
get_zip_opt(Rest, Opts#list_dir_opts{extra = What});
false ->
throw({bad_option, O})
end;
%% get_list_dir_opt([{file_output, F} | Rest], Opts) ->
%% get_list_dir_opt(Rest, Opts#list_dir_opts{file_output = F});
%% get_list_dir_opt([{file_filter, F} | Rest], Opts) ->
%% get_list_dir_opt(Rest, Opts#list_dir_opts{file_filter = F});
get_list_dir_opt([Unknown | _Rest], _Opts) ->
throw({bad_option, Unknown}).
get_zip_opt([], Opts) ->
Opts;
get_zip_opt([verbose | Rest], Opts) ->
get_zip_opt(Rest, Opts#zip_opts{feedback = fun verbose_zip/1});
get_zip_opt([cooked | Rest], #zip_opts{open_opts = OpO} = Opts) ->
get_zip_opt(Rest, Opts#zip_opts{open_opts = OpO -- [raw]});
get_zip_opt([memory | Rest], Opts) ->
get_zip_opt(Rest, Opts#zip_opts{output = fun binary_io/2});
get_zip_opt([{cwd, CWD} | Rest], Opts) ->
get_zip_opt(Rest, Opts#zip_opts{cwd = CWD});
get_zip_opt([{comment, C} | Rest], Opts) ->
get_zip_opt(Rest, Opts#zip_opts{comment = C});
get_zip_opt([{compress, Which} = O| Rest], Opts) ->
Which2 =
case Which of
all ->
all;
Suffixes when is_list(Suffixes) ->
lists:usort(Suffixes);
{add, Suffixes} when is_list(Suffixes) ->
lists:usort(Opts#zip_opts.compress ++ Suffixes);
{del, Suffixes} when is_list(Suffixes) ->
lists:usort(Opts#zip_opts.compress -- Suffixes);
_ ->
throw({bad_option, O})
end,
get_zip_opt(Rest, Opts#zip_opts{compress = Which2});
get_zip_opt([{uncompress, Which} = O| Rest], Opts) ->
Which2 =
case Which of
all ->
all;
Suffixes when is_list(Suffixes) ->
lists:usort(Suffixes);
{add, Suffixes} when is_list(Suffixes) ->
lists:usort(Opts#zip_opts.uncompress ++ Suffixes);
{del, Suffixes} when is_list(Suffixes) ->
lists:usort(Opts#zip_opts.uncompress -- Suffixes);
_ ->
throw({bad_option, O})
end,
get_zip_opt(Rest, Opts#zip_opts{uncompress = Which2});
get_zip_opt([{extra, What} = O| Rest], Opts) when is_list(What) ->
case lists:all(fun(E) -> lists:member(E, ?EXTRA_OPTIONS) end, What) of
true ->
get_zip_opt(Rest, Opts#zip_opts{extra = What});
false ->
throw({bad_option, O})
end;
get_zip_opt([Unknown | _Rest], _Opts) ->
throw({bad_option, Unknown}).
%% feedback funs
silent(_) -> ok.
verbose_unzip(FN) ->
io:format("extracting: ~ts\n", [io_lib:write_string(FN)]).
verbose_zip(FN) ->
io:format("adding: ~ts\n", [io_lib:write_string(FN)]).
%% file filter funs
all(_) -> true.
file_in_list({#zip_file{name = FileName},_}, List) ->