View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker and Matt Lilley
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           https://www.swi-prolog.org
    6    Copyright (c)  2012-2026, VU University Amsterdam
    7                              SWI-Prolog Solutions b.v.
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(archive,
   37          [ archive_open/3,             % +Stream, -Archive, +Options
   38            archive_open/4,             % +Stream, +Mode, -Archive, +Options
   39            archive_create/3,           % +OutputFile, +InputFileList, +Options
   40            archive_close/1,            % +Archive
   41            archive_property/2,         % +Archive, ?Property
   42            archive_next_header/2,      % +Archive, -Name
   43            archive_open_entry/2,       % +Archive, -EntryStream
   44            archive_header_property/2,  % +Archive, ?Property
   45            archive_set_header_property/2,      % +Archive, +Property
   46            archive_extract/3,          % +Archive, +Dir, +Options
   47
   48            archive_entries/2,          % +Archive, -Entries
   49            archive_data_stream/3,      % +Archive, -DataStream, +Options
   50            archive_foldl/4             % :Goal, +Archive, +State0, -State
   51          ]).   52:- autoload(library(error),
   53            [existence_error/2, domain_error/2, must_be/2, permission_error/3]).   54:- autoload(library(filesex), [directory_file_path/3, make_directory_path/1]).   55:- autoload(library(lists), [member/2, append/3, selectchk/3]).   56:- autoload(library(apply), [maplist/3, partition/4]).   57:- autoload(library(option), [option/3, option/2, merge_options/3]).   58
   59:- meta_predicate
   60    archive_foldl(4, +, +, -).   61
   62/** <module> Access several archive formats
   63
   64This library uses _libarchive_ to access   a variety of archive formats.
   65The following example lists the entries in an archive:
   66
   67  ```
   68  list_archive(File) :-
   69      setup_call_cleanup(
   70          archive_open(File, Archive, []),
   71          (   repeat,
   72              (   archive_next_header(Archive, Path)
   73              ->  format('~w~n', [Path]),
   74                  fail
   75              ;   !
   76              )
   77          ),
   78          archive_close(Archive)).
   79  ```
   80
   81Here  is an  alternative way  of  doing this,  using archive_foldl/4,  a
   82higher level predicate.
   83
   84  ```
   85  list_archive2(File) :-
   86      list_archive(File, Headers),
   87      maplist(writeln, Headers).
   88
   89  list_archive2(File, Headers) :-
   90      archive_foldl(add_header, File, Headers, []).
   91
   92  add_header(Path, _, [Path|Paths], Paths).
   93  ```
   94
   95Here is another example which counts the files in the archive and prints
   96file  type  information, also using archive_foldl/4:
   97
   98  ```
   99  print_entry(Path, Handle, Cnt0, Cnt1) :-
  100      archive_header_property(Handle, filetype(Type)),
  101      format('File ~w is of type ~w~n', [Path, Type]),
  102      Cnt1 is Cnt0 + 1.
  103
  104  list_archive_headers(File) :-
  105      archive_foldl(print_entry, File, 0, FileCount),
  106      format('We have ~w files', [FileCount]).
  107  ```
  108
  109@see https://github.com/libarchive/libarchive/
  110*/
  111
  112:- use_foreign_library(foreign(archive4pl)).  113
  114%!  archive_open(+Data, -Archive, +Options) is det.
  115%
  116%   Wrapper around archive_open/4 that opens the archive in read mode.
  117
  118archive_open(Stream, Archive, Options) :-
  119    archive_open(Stream, read, Archive, Options).
  120
  121:- predicate_options(archive_open/4, 4,
  122                     [ close_parent(boolean),
  123                       filters(list(oneof([all,bzip2,compress,gzip,grzip,lrzip,
  124                                     lzip,lzma,lzop,none,rpm,uu,xz]))),
  125                       formats(list(oneof([all,'7zip',ar,cab,cpio,empty,gnutar,
  126                                     iso9660,lha,mtree,rar,raw,tar,xar,zip]))),
  127                       filter(oneof([all,bzip2,compress,gzip,grzip,lrzip,
  128                                     lzip,lzma,lzop,none,rpm,uu,xz])),
  129                       format(oneof([all,'7zip',ar,cab,cpio,empty,gnutar,
  130                                     iso9660,lha,mtree,rar,raw,tar,xar,zip])),
  131                       compression(oneof([all,bzip2,compress,gzip,grzip,lrzip,
  132                                     lzip,lzma,lzop,none,rpm,uu,xz]))
  133                     ]).  134:- predicate_options(archive_create/3, 3,
  135                     [ directory(atom),
  136                       pass_to(archive_open/4, 4)
  137                     ]).  138
  139%!  archive_open(+Data, +Mode, -Archive, +Options) is det.
  140%
  141%   Open the  archive in  Data and  unify Archive with  a handle  to the
  142%   opened archive.  Data is either a  file name (as accepted by open/4)
  143%   or a stream  that has been opened with the  option type(binary).  If
  144%   Data  is an  already  open  stream, the  caller  is responsible  for
  145%   closing it  (but see option  close_parent(true)) and must  not close
  146%   the stream  until after archive_close/1  is called.  Mode  is either
  147%   `read` or  `write`.  Details are controlled  by Options.  Typically,
  148%   the option close_parent(true) is used  to also close the Data stream
  149%   if the archive  is closed using archive_close/1.   For other options
  150%   when reading, the defaults are typically fine - for writing, a valid
  151%   format  and   optional  filters  must  be   specified.   The  option
  152%   format(raw) must be  used to process compressed streams  that do not
  153%   contain explicit  entries (e.g.,  gzip'ed data)  unambibuously.  The
  154%   =raw=  format creates  a _pseudo  archive_ holding  a single  member
  155%   named =data=.
  156%
  157%     * close_parent(+Boolean)
  158%     If this option is =true=  (default =false=), Data stream is closed
  159%     when archive_close/1 is called on Archive. If Data is a file name,
  160%     the default is =true=.
  161%
  162%     * filters(+Filters)
  163%     Support the filters in the list Filters.  In read mode, if no
  164%     filter is provided, =all= is assumed.  In write mode, =none= is
  165%     assumed and at most one filter is allowed.  Supported values are
  166%     =all=, =bzip2=, =compress=, =gzip=, =grzip=, =lrzip=, =lzip=,
  167%     =lzma=, =lzop=, =none=, =rpm=, =uu= and =xz=.
  168%
  169%     * formats(+Formats)
  170%     Support the formats in the list Formats.  In write mode, you must
  171%     supply a single format.  If no format is provided, =all= is
  172%     assumed for read mode.  Note that =all= does *not* include =raw=
  173%     and =mtree=.  To open both archive and non-archive files, =all=
  174%     together with =raw= and/or =mtree= must be specified.  Supported
  175%     values are =all=, =7zip=, =ar=, =cab=, =cpio=, =empty=, =gnutar=,
  176%     =iso9660=, =lha=, =mtree=, =rar=, =raw=, =tar=, =xar= and =zip=.
  177%
  178%     * filter(+Filter)
  179%     * format(+Format)
  180%     * compression(+Filter)
  181%     Deprecated.  Add a single filter or format.  Repeating these
  182%     options to support multiple filters/formats is deprecated in
  183%     favour of filters/1 and formats/1.  compression/1 is a synonym for
  184%     filter/1.
  185%
  186%   Note that the  actually supported compression types  and formats may
  187%   vary  depending  on the  version  and  installation options  of  the
  188%   underlying libarchive  library.  This  predicate raises a  domain or
  189%   permission error if  the (explicitly) requested format  or filter is
  190%   not supported.
  191%
  192%   @error  domain_error(filter, Filter) if the requested
  193%           filter is invalid (e.g., `all` for writing).
  194%   @error  domain_error(format, Format) if the requested
  195%           format type is not supported.
  196%   @error  permission_error(set, filter, Filter) if the requested
  197%           filter is not supported.
  198
  199archive_open(stream(Stream), Mode, Archive, Options) :-
  200    !,
  201    archive_open_stream(Stream, Mode, Archive, Options).
  202archive_open(Stream, Mode, Archive, Options) :-
  203    is_stream(Stream),
  204    !,
  205    archive_open_stream(Stream, Mode, Archive, Options).
  206archive_open(File, Mode, Archive, Options) :-
  207    open(File, Mode, Stream, [type(binary)]),
  208    merge_options([close_parent(true)], Options, Options1),
  209    catch(archive_open_stream(Stream, Mode, Archive, Options1),
  210          E, (close(Stream, [force(true)]), throw(E))).
  211
  212%!  archive_open_stream(+Stream, +Mode, -Archive, +Options) is det.
  213%
  214%   Wrapper around the foreign '$archive_open_stream'/4 that canonicalises
  215%   the options: multiple filter/compression and format options are folded
  216%   into a single filters(List) and formats(List) option.
  217
  218archive_open_stream(Stream, Mode, Archive, Options0) :-
  219    archive_options(Options0, Options),
  220    '$archive_open_stream'(Stream, Mode, Archive, Options).
  221
  222%!  archive_options(+Options0, -Options) is det.
  223%
  224%   Fold the (possibly repeated) filter/1, compression/1 and format/1
  225%   options into a single filters/1 and formats/1 list option, as
  226%   expected by the foreign code.  Repeating filter or format is
  227%   deprecated in favour of the list form.
  228
  229archive_options(Options0, Options) :-
  230    fold_options([filter,compression], filters, Options0, Options1),
  231    fold_options([format], formats, Options1, Options).
  232
  233fold_options(Names, ListName, Options0, Options) :-
  234    partition(option_of(Names), Options0, Singulars, Rest),
  235    (   Singulars == []
  236    ->  Options = Options0
  237    ;   maplist(arg(1), Singulars, Values),
  238        (   Singulars = [_,_|_]
  239        ->  print_message(warning, archive(deprecated_repeat(ListName)))
  240        ;   true
  241        ),
  242        (   ListOpt =.. [ListName, Old],
  243            selectchk(ListOpt, Rest, Rest1)
  244        ->  append(Old, Values, All)
  245        ;   Rest1 = Rest,
  246            All = Values
  247        ),
  248        Merged =.. [ListName, All],
  249        Options = [Merged|Rest1]
  250    ).
  251
  252option_of(Names, Option) :-
  253    compound(Option),
  254    functor(Option, Name, 1),
  255    memberchk(Name, Names).
  256
  257
  258%!  archive_close(+Archive) is det.
  259%
  260%   Close  the   archive.   If   close_parent(true)  was   specified  in
  261%   archive_open/4, the underlying entry stream  is closed too. If there
  262%   is an  entry opened with archive_open_entry/2,  actually closing the
  263%   archive is  delayed until  the stream associated  with the  entry is
  264%   closed.   This can  be used  to open  a stream  to an  archive entry
  265%   without having to worry about closing the archive:
  266%
  267%     ```
  268%     archive_open_named(ArchiveFile, EntryName, Stream) :-
  269%         archive_open(ArchiveFile, Archive, []),
  270%         archive_next_header(Archive, EntryName),
  271%         archive_open_entry(Archive, Stream),
  272%         archive_close(Archive).
  273%     ```
  274
  275
  276%!  archive_property(+Handle, ?Property) is nondet.
  277%
  278%   True when Property is a property  of the archive Handle. Defined
  279%   properties are:
  280%
  281%     * filters(List)
  282%     True when the indicated filters are applied before reaching
  283%     the archive format.
  284
  285archive_property(Handle, Property) :-
  286    defined_archive_property(Property),
  287    Property =.. [Name,Value],
  288    archive_property(Handle, Name, Value).
  289
  290defined_archive_property(filter(_)).
  291
  292
  293%!  archive_next_header(+Handle, -Name) is semidet.
  294%
  295%   Forward to the next entry of the  archive for which Name unifies
  296%   with the pathname of the entry. Fails   silently  if the end  of
  297%   the  archive  is  reached  before  success.  Name  is  typically
  298%   specified if a  single  entry  must   be  accessed  and  unbound
  299%   otherwise. The following example opens  a   Prolog  stream  to a
  300%   given archive entry. Note that  _Stream_   must  be closed using
  301%   close/1 and the archive  must   be  closed using archive_close/1
  302%   after the data has been used.   See also setup_call_cleanup/3.
  303%
  304%     ```
  305%     open_archive_entry(ArchiveFile, EntryName, Stream) :-
  306%         open(ArchiveFile, read, In, [type(binary)]),
  307%         archive_open(In, Archive, [close_parent(true)]),
  308%         archive_next_header(Archive, EntryName),
  309%         archive_open_entry(Archive, Stream).
  310%     ```
  311%
  312%   @error permission_error(next_header, archive, Handle) if a
  313%   previously opened entry is not closed.
  314
  315%!  archive_open_entry(+Archive, -Stream) is det.
  316%
  317%   Open the current entry as a stream. Stream must be closed.
  318%   If the stream is not closed before the next call to
  319%   archive_next_header/2, a permission error is raised.
  320
  321
  322%!  archive_set_header_property(+Archive, +Property)
  323%
  324%   Set Property of the current header.  Write-mode only. Defined
  325%   properties are:
  326%
  327%     * filetype(-Type)
  328%     Type is one of =file=, =link=, =socket=, =character_device=,
  329%     =block_device=, =directory= or =fifo=.  It appears that this
  330%     library can also return other values.  These are returned as
  331%     an integer.
  332%     * mtime(-Time)
  333%     True when entry was last modified at time.
  334%     * size(-Bytes)
  335%     True when entry is Bytes long.
  336%     * link_target(-Target)
  337%     Target for a link. Currently only supported for symbolic
  338%     links.
  339
  340%!  archive_header_property(+Archive, ?Property)
  341%
  342%   True when Property is a property of the current header.  Defined
  343%   properties are:
  344%
  345%     * filetype(-Type)
  346%     Type is one of =file=, =link=, =socket=, =character_device=,
  347%     =block_device=, =directory= or =fifo=.  It appears that this
  348%     library can also return other values.  These are returned as
  349%     an integer.
  350%     * mtime(-Time)
  351%     True when entry was last modified at time.
  352%     * size(-Bytes)
  353%     True when entry is Bytes long.
  354%     * link_target(-Target)
  355%     Target for a link. Currently only supported for symbolic
  356%     links.
  357%     * format(-Format)
  358%     Provides the name of the archive format applicable to the
  359%     current entry.  The returned value is the lowercase version
  360%     of the output of archive_format_name().
  361%     * permissions(-Integer)
  362%     True when entry has the indicated permission mask.
  363
  364archive_header_property(Archive, Property) :-
  365    (   nonvar(Property)
  366    ->  true
  367    ;   header_property(Property)
  368    ),
  369    archive_header_prop_(Archive, Property).
  370
  371header_property(filetype(_)).
  372header_property(mtime(_)).
  373header_property(size(_)).
  374header_property(link_target(_)).
  375header_property(format(_)).
  376header_property(permissions(_)).
  377
  378
  379%!  archive_extract(+ArchiveFile, +Dir, +Options)
  380%
  381%   Extract files from the given archive into Dir. Supported
  382%   options:
  383%
  384%     * remove_prefix(+Prefix)
  385%     Strip Prefix from all entries before extracting. If Prefix
  386%     is a list, then each prefix is tried in order, succeding at
  387%     the first one that matches. If no prefixes match, an error
  388%     is reported. If Prefix is an atom, then that prefix is removed.
  389%     * exclude(+ListOfPatterns)
  390%     Ignore members that match one of the given patterns.
  391%     Patterns are handed to wildcard_match/2.
  392%     * include(+ListOfPatterns)
  393%     Include members that match one of the given patterns.
  394%     Patterns are handed to wildcard_match/2. The `exclude`
  395%     options takes preference if a member matches both the `include`
  396%     and the `exclude` option.
  397%
  398%   Only regular files are extracted.  Entries whose path is absolute
  399%   or contains a `..` segment are not extracted to avoid writing
  400%   outside Dir.
  401%
  402%   @error  existence_error(directory, Dir) if Dir does not exist
  403%           or is not a directory.
  404%   @error  domain_error(path_prefix(Prefix), Path) if a path in
  405%           the archive does not start with Prefix
  406%   @error  permission_error(extract, archive_entry, Path) if the
  407%           path of a member is absolute or contains `..`.
  408%   @tbd    Add options
  409
  410archive_extract(Archive, Dir, Options) :-
  411    (   exists_directory(Dir)
  412    ->  true
  413    ;   existence_error(directory, Dir)
  414    ),
  415    setup_call_cleanup(
  416        archive_open(Archive, Handle, Options),
  417        extract(Handle, Dir, Options),
  418        archive_close(Handle)).
  419
  420extract(Archive, Dir, Options) :-
  421    archive_next_header(Archive, Path),
  422    !,
  423    option(include(InclPatterns), Options, ['*']),
  424    option(exclude(ExclPatterns), Options, []),
  425    (   archive_header_property(Archive, filetype(file)),
  426        \+ matches(ExclPatterns, Path),
  427        matches(InclPatterns, Path)
  428    ->  archive_header_property(Archive, permissions(Perm)),
  429        remove_prefix(Options, Path, ExtractPath),
  430        safe_extract_path(ExtractPath),
  431        directory_file_path(Dir, ExtractPath, Target),
  432        file_directory_name(Target, FileDir),
  433        make_directory_path(FileDir),
  434        setup_call_cleanup(
  435            archive_open_entry(Archive, In),
  436            setup_call_cleanup(
  437                open(Target, write, Out, [type(binary)]),
  438                copy_stream_data(In, Out),
  439                close(Out)),
  440            close(In)),
  441        set_permissions(Perm, Target)
  442    ;   true
  443    ),
  444    extract(Archive, Dir, Options).
  445extract(_, _, _).
  446
  447%!  safe_extract_path(+Path) is det.
  448%
  449%   Raise a permission error if Path is not a relative path that stays
  450%   inside the target directory.
  451
  452safe_extract_path(Path) :-
  453    (   is_absolute_file_name(Path)
  454    ->  unsafe_path(Path)
  455    ;   current_prolog_flag(windows, true),
  456        sub_atom(Path, 1, 1, _, :)          % C:foo is drive-relative
  457    ->  unsafe_path(Path)
  458    ;   path_separators(Seps),
  459        split_string(Path, Seps, "", Segments),
  460        memberchk("..", Segments)
  461    ->  unsafe_path(Path)
  462    ;   true
  463    ).
  464
  465path_separators("/\\") :-
  466    current_prolog_flag(windows, true),
  467    !.
  468path_separators("/").
  469
  470unsafe_path(Path) :-
  471    permission_error(extract, archive_entry, Path).
  472
  473%!  matches(+Patterns, +Path) is semidet.
  474%
  475%   True when Path matches a pattern in Patterns.
  476
  477matches([], _Path) :-
  478    !,
  479    fail.
  480matches(Patterns, Path) :-
  481    split_string(Path, "/", "/", Parts),
  482    member(Segment, Parts),
  483    Segment \== "",
  484    member(Pattern, Patterns),
  485    wildcard_match(Pattern, Segment),
  486    !.
  487
  488remove_prefix(Options, Path, ExtractPath) :-
  489    (   option(remove_prefix(Remove), Options)
  490    ->  (   is_list(Remove)
  491        ->  (   member(P, Remove),
  492                atom_concat(P, ExtractPath, Path)
  493            ->  true
  494            ;   domain_error(path_prefix(Remove), Path)
  495            )
  496        ;   (   atom_concat(Remove, ExtractPath, Path)
  497            ->  true
  498            ;   domain_error(path_prefix(Remove), Path)
  499            )
  500        )
  501    ;   ExtractPath = Path
  502    ).
  503
  504%!  set_permissions(+Perm:integer, +Target:atom)
  505%
  506%   Restore the permissions.  Currently only restores the executable
  507%   permission.
  508
  509set_permissions(Perm, Target) :-
  510    Perm /\ 0o100 =\= 0,
  511    !,
  512    '$mark_executable'(Target).
  513set_permissions(_, _).
  514
  515
  516                 /*******************************
  517                 *    HIGH LEVEL PREDICATES     *
  518                 *******************************/
  519
  520%!  archive_entries(+Archive, -Paths) is det.
  521%
  522%   True when Paths is a list of pathnames appearing in Archive.
  523
  524archive_entries(Archive, Paths) :-
  525    setup_call_cleanup(
  526        archive_open(Archive, Handle, []),
  527        contents(Handle, Paths),
  528        archive_close(Handle)).
  529
  530contents(Handle, [Path|T]) :-
  531    archive_next_header(Handle, Path),
  532    !,
  533    contents(Handle, T).
  534contents(_, []).
  535
  536%!  archive_data_stream(+Archive, -DataStream, +Options) is nondet.
  537%
  538%   True when DataStream  is  a  stream   to  a  data  object inside
  539%   Archive.  This  predicate  transparently   unpacks  data  inside
  540%   _possibly nested_ archives, e.g., a _tar_   file  inside a _zip_
  541%   file. It applies the appropriate  decompression filters and thus
  542%   ensures that Prolog  reads  the   plain  data  from  DataStream.
  543%   DataStream must be closed after the  content has been processed.
  544%   Backtracking opens the next member of the (nested) archive. This
  545%   predicate processes the following options:
  546%
  547%     - meta_data(-Data:list(dict))
  548%     If provided, Data is unified with a list of filters applied to
  549%     the (nested) archive to open the current DataStream. The first
  550%     element describes the outermost archive. Each Data dict
  551%     contains the header properties (archive_header_property/2) as
  552%     well as the keys:
  553%
  554%       - filters(Filters:list(atom))
  555%       Filter list as obtained from archive_property/2
  556%       - name(Atom)
  557%       Name of the entry.
  558%
  559%   Non-archive files are handled as pseudo-archives that hold a
  560%   single stream.  This is implemented by using archive_open/3 with
  561%   the options `[format(all),format(raw)]`.
  562
  563archive_data_stream(Archive, DataStream, Options) :-
  564    option(meta_data(MetaData), Options, _),
  565    archive_content(Archive, DataStream, MetaData, []).
  566
  567archive_content(Archive, Entry, [EntryMetadata|PipeMetadataTail], PipeMetadata2) :-
  568    archive_property(Archive, filter(Filters)),
  569    repeat,
  570    (   archive_next_header(Archive, EntryName)
  571    ->  findall(EntryProperty,
  572                archive_header_property(Archive, EntryProperty),
  573                EntryProperties),
  574        dict_create(EntryMetadata, archive_meta_data,
  575                    [ filters(Filters),
  576                      name(EntryName)
  577                    | EntryProperties
  578                    ]),
  579        (   EntryMetadata.filetype == file
  580        ->  archive_open_entry(Archive, Entry0),
  581            (   EntryName == data,
  582                EntryMetadata.format == raw
  583            ->  % This is the last entry in this nested branch.
  584                % We therefore close the choicepoint created by repeat/0.
  585                % Not closing this choicepoint would cause
  586                % archive_next_header/2 to throw an exception.
  587                !,
  588                PipeMetadataTail = PipeMetadata2,
  589                Entry = Entry0
  590            ;   PipeMetadataTail = PipeMetadata1,
  591                open_substream(Entry0,
  592                               Entry,
  593                               PipeMetadata1,
  594                               PipeMetadata2)
  595            )
  596        ;   fail
  597        )
  598    ;   !,
  599        fail
  600    ).
  601
  602open_substream(In, Entry, ArchiveMetadata, PipeTailMetadata) :-
  603    setup_call_cleanup(
  604        archive_open(stream(In),
  605                     Archive,
  606                     [ close_parent(true),
  607                       format(all),
  608                       format(raw)
  609                     ]),
  610        archive_content(Archive, Entry, ArchiveMetadata, PipeTailMetadata),
  611        archive_close(Archive)).
  612
  613
  614%!  archive_create(+OutputFile, +InputFiles, +Options) is det.
  615%
  616%   Convenience predicate to create an   archive  in OutputFile with
  617%   data from a list of InputFiles and the given Options.
  618%
  619%   Besides  options  supported  by  archive_open/4,  the  following
  620%   options are supported:
  621%
  622%     * directory(+Directory)
  623%     Changes the directory before adding input files. If this is
  624%     specified,   paths of  input  files   must   be relative to
  625%     Directory and archived files will not have Directory
  626%     as leading path. This is to simulate =|-C|= option of
  627%     the =tar= program.
  628%
  629%     * format(+Format)
  630%     Write mode supports the following formats: `7zip`, `cpio`,
  631%     `gnutar`, `iso9660`, `xar` and `zip`.  Note that a particular
  632%     installation may support only a subset of these, depending on
  633%     the configuration of `libarchive`.
  634
  635archive_create(OutputFile, InputFiles, Options) :-
  636    must_be(list(text), InputFiles),
  637    option(directory(BaseDir), Options, '.'),
  638    setup_call_cleanup(
  639        archive_open(OutputFile, write, Archive, Options),
  640        archive_create_1(Archive, BaseDir, BaseDir, InputFiles, top),
  641        archive_close(Archive)).
  642
  643archive_create_1(_, _, _, [], _) :- !.
  644archive_create_1(Archive, Base, Current, ['.'|Files], sub) :-
  645    !,
  646    archive_create_1(Archive, Base, Current, Files, sub).
  647archive_create_1(Archive, Base, Current, ['..'|Files], Where) :-
  648    !,
  649    archive_create_1(Archive, Base, Current, Files, Where).
  650archive_create_1(Archive, Base, Current, [File|Files], Where) :-
  651    directory_file_path(Current, File, Filename),
  652    archive_create_2(Archive, Base, Filename),
  653    archive_create_1(Archive, Base, Current, Files, Where).
  654
  655archive_create_2(Archive, Base, Directory) :-
  656    exists_directory(Directory),
  657    !,
  658    entry_name(Base, Directory, Directory0),
  659    archive_next_header(Archive, Directory0),
  660    time_file(Directory, Time),
  661    archive_set_header_property(Archive, mtime(Time)),
  662    archive_set_header_property(Archive, filetype(directory)),
  663    archive_open_entry(Archive, EntryStream),
  664    close(EntryStream),
  665    directory_files(Directory, Files),
  666    archive_create_1(Archive, Base, Directory, Files, sub).
  667archive_create_2(Archive, Base, Filename) :-
  668    entry_name(Base, Filename, Filename0),
  669    archive_next_header(Archive, Filename0),
  670    size_file(Filename, Size),
  671    time_file(Filename, Time),
  672    archive_set_header_property(Archive, size(Size)),
  673    archive_set_header_property(Archive, mtime(Time)),
  674    setup_call_cleanup(
  675        archive_open_entry(Archive, EntryStream),
  676        setup_call_cleanup(
  677            open(Filename, read, DataStream, [type(binary)]),
  678            copy_stream_data(DataStream, EntryStream),
  679            close(DataStream)),
  680        close(EntryStream)).
  681
  682entry_name('.', Name, Name) :- !.
  683entry_name(Base, Name, EntryName) :-
  684    directory_file_path(Base, EntryName, Name).
  685
  686%!  archive_foldl(:Goal, +Archive, +State0, -State).
  687%
  688%   Operates like foldl/4 but for the entries   in the archive. For each
  689%   member of the archive, Goal called   as `call(:Goal, +Path, +Handle,
  690%   +S0,  -S1).  Here,  `S0`  is  current  state  of  the  _accumulator_
  691%   (starting  with  State0)  and  `S1`  is    the  next  state  of  the
  692%   accumulator, producing State after the last member of the archive.
  693%
  694%   @see archive_header_property/2, archive_open/4.
  695%
  696%   @arg Archive File name or stream to be given to archive_open/[3,4].
  697
  698archive_foldl(Goal, Archive, State0, State) :-
  699    setup_call_cleanup(
  700        archive_open(Archive, Handle, [close_parent(true)]),
  701        archive_foldl_(Goal, Handle, State0, State),
  702        archive_close(Handle)
  703    ).
  704
  705archive_foldl_(Goal, Handle, State0, State) :-
  706    (   archive_next_header(Handle, Path)
  707    ->  call(Goal, Path, Handle, State0, State1),
  708        archive_foldl_(Goal, Handle, State1, State)
  709    ;   State = State0
  710    ).
  711
  712
  713		 /*******************************
  714		 *           MESSAGES		*
  715		 *******************************/
  716
  717:- multifile prolog:error_message//1, prolog:message//1.  718
  719prolog:error_message(archive_error(Code, Message)) -->
  720    [ 'Archive error (code ~p): ~w'-[Code, Message] ].
  721
  722prolog:message(archive(deprecated_repeat(ListName))) -->
  723    [ 'archive_open/4: repeating the filter/format option is deprecated; \c
  724       use ~w(List) instead'-[ListName] ]