View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           https://www.swi-prolog.org
    6    Copyright (c)  2012-2024, VU University Amsterdam
    7                              CWI, Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(prolog_pack,
   38          [ pack_list_installed/0,
   39            pack_info/1,                % +Name
   40            pack_list/1,                % +Keyword
   41            pack_list/2,                % +Query, +Options
   42            pack_search/1,              % +Keyword
   43            pack_install/1,             % +Name
   44            pack_install/2,             % +Name, +Options
   45            pack_install_local/3,       % :Spec, +Dir, +Options
   46            pack_upgrade/1,             % +Name
   47            pack_rebuild/1,             % +Name
   48            pack_rebuild/0,             % All packages
   49            pack_remove/1,              % +Name
   50            pack_remove/2,              % +Name, +Options
   51            pack_publish/2,             % +URL, +Options
   52            pack_property/2             % ?Name, ?Property
   53          ]).   54:- use_module(library(apply)).   55:- use_module(library(error)).   56:- use_module(library(option)).   57:- use_module(library(readutil)).   58:- use_module(library(lists)).   59:- use_module(library(filesex)).   60:- use_module(library(xpath)).   61:- use_module(library(settings)).   62:- use_module(library(uri)).   63:- use_module(library(dcg/basics)).   64:- use_module(library(dcg/high_order)).   65:- use_module(library(http/http_open)).   66:- use_module(library(json)).   67:- use_module(library(http/http_client), []).   68:- use_module(library(debug), [assertion/1]).   69:- use_module(library(pairs),
   70              [pairs_keys/2, map_list_to_pairs/3, pairs_values/2]).   71:- autoload(library(git)).   72:- autoload(library(sgml)).   73:- autoload(library(sha)).   74:- autoload(library(build/tools)).   75:- autoload(library(ansi_term), [ansi_format/3]).   76:- autoload(library(pprint), [print_term/2]).   77:- autoload(library(prolog_versions), [require_version/3, cmp_versions/3]).   78:- autoload(library(ugraphs), [vertices_edges_to_ugraph/3, ugraph_layers/2]).   79:- autoload(library(process), [process_which/2]).   80:- autoload(library(aggregate), [aggregate_all/3]).   81
   82:- meta_predicate
   83    pack_install_local(2, +, +).

A package manager for Prolog

The library(prolog_pack) provides the SWI-Prolog package manager. This library lets you inspect installed packages, install packages, remove packages, etc. This library complemented by the built-in predicates such as attach_packs/2 that makes installed packages available as libraries.

The important functionality of this library is encapsulated in the app pack. For help, run

swipl pack help
   98                 /*******************************
   99                 *          CONSTANTS           *
  100                 *******************************/
  101
  102:- setting(server, atom, 'https://www.swi-prolog.org/pack/',
  103           'Server to exchange pack information').  104
  105
  106		 /*******************************
  107		 *       LOCAL DECLARATIONS	*
  108		 *******************************/
  109
  110:- op(900, xfx, @).                     % Token@Version
  111
  112:- meta_predicate det_if(0,0).  113
  114                 /*******************************
  115                 *         PACKAGE INFO         *
  116                 *******************************/
 current_pack(?Pack) is nondet
 current_pack(?Pack, ?Dir) is nondet
True if Pack is a currently installed pack.
  123current_pack(Pack) :-
  124    current_pack(Pack, _).
  125
  126current_pack(Pack, Dir) :-
  127    '$pack':pack(Pack, Dir).
 pack_list_installed is det
List currently installed packages and report possible dependency issues.
  134pack_list_installed :-
  135    pack_list('', [installed(true)]),
  136    validate_dependencies.
 pack_info(+Pack)
Print more detailed information about Pack.
  142pack_info(Name) :-
  143    pack_info(info, Name).
  144
  145pack_info(Level, Name) :-
  146    must_be(atom, Name),
  147    findall(Info, pack_info(Name, Level, Info), Infos0),
  148    (   Infos0 == []
  149    ->  print_message(warning, pack(no_pack_installed(Name))),
  150        fail
  151    ;   true
  152    ),
  153    findall(Def,  pack_default(Level, Infos, Def), Defs),
  154    append(Infos0, Defs, Infos1),
  155    sort(Infos1, Infos),
  156    show_info(Name, Infos, [info(Level)]).
  157
  158
  159show_info(_Name, _Properties, Options) :-
  160    option(silent(true), Options),
  161    !.
  162show_info(_Name, _Properties, Options) :-
  163    option(show_info(false), Options),
  164    !.
  165show_info(Name, Properties, Options) :-
  166    option(info(list), Options),
  167    !,
  168    memberchk(title(Title), Properties),
  169    memberchk(version(Version), Properties),
  170    format('i ~w@~w ~28|- ~w~n', [Name, Version, Title]).
  171show_info(Name, Properties, _) :-
  172    !,
  173    print_property_value('Package'-'~w', [Name]),
  174    findall(Term, pack_level_info(info, Term, _, _), Terms),
  175    maplist(print_property(Properties), Terms).
  176
  177print_property(_, nl) :-
  178    !,
  179    format('~n').
  180print_property(Properties, Term) :-
  181    findall(Term, member(Term, Properties), Terms),
  182    Terms \== [],
  183    !,
  184    pack_level_info(_, Term, LabelFmt, _Def),
  185    (   LabelFmt = Label-FmtElem
  186    ->  true
  187    ;   Label = LabelFmt,
  188        FmtElem = '~w'
  189    ),
  190    multi_valued(Terms, FmtElem, FmtList, Values),
  191    atomic_list_concat(FmtList, ', ', Fmt),
  192    print_property_value(Label-Fmt, Values).
  193print_property(_, _).
  194
  195multi_valued([H], LabelFmt, [LabelFmt], Values) :-
  196    !,
  197    H =.. [_|Values].
  198multi_valued([H|T], LabelFmt, [LabelFmt|LT], Values) :-
  199    H =.. [_|VH],
  200    append(VH, MoreValues, Values),
  201    multi_valued(T, LabelFmt, LT, MoreValues).
  202
  203
  204pvalue_column(31).
  205print_property_value(Prop-Fmt, Values) :-
  206    !,
  207    pvalue_column(C),
  208    ansi_format(comment, '% ~w:~t~*|', [Prop, C]),
  209    ansi_format(code, Fmt, Values),
  210    ansi_format([], '~n', []).
  211
  212pack_info(Name, Level, Info) :-
  213    '$pack':pack(Name, BaseDir),
  214    pack_dir_info(BaseDir, Level, Info).
  215
  216pack_dir_info(BaseDir, Level, Info) :-
  217    (   Info = directory(BaseDir)
  218    ;   pack_info_term(BaseDir, Info)
  219    ),
  220    pack_level_info(Level, Info, _Format, _Default).
  221
  222:- public pack_level_info/4.                    % used by web-server
  223
  224pack_level_info(_,    title(_),         'Title',                   '<no title>').
  225pack_level_info(_,    version(_),       'Installed version',       '<unknown>').
  226pack_level_info(info, automatic(_),	'Automatic (dependency only)', -).
  227pack_level_info(info, directory(_),     'Installed in directory',  -).
  228pack_level_info(info, link(_),		'Installed as link to'-'~w', -).
  229pack_level_info(info, built(_,_),	'Built on'-'~w for SWI-Prolog ~w', -).
  230pack_level_info(info, author(_, _),     'Author'-'~w <~w>',        -).
  231pack_level_info(info, maintainer(_, _), 'Maintainer'-'~w <~w>',    -).
  232pack_level_info(info, packager(_, _),   'Packager'-'~w <~w>',      -).
  233pack_level_info(info, home(_),          'Home page',               -).
  234pack_level_info(info, download(_),      'Download URL',            -).
  235pack_level_info(_,    provides(_),      'Provides',                -).
  236pack_level_info(_,    requires(_),      'Requires',                -).
  237pack_level_info(_,    conflicts(_),     'Conflicts with',          -).
  238pack_level_info(_,    replaces(_),      'Replaces packages',       -).
  239pack_level_info(info, library(_),	'Provided libraries',      -).
  240pack_level_info(info, autoload(_),	'Autoload',                -).
  241
  242pack_default(Level, Infos, Def) :-
  243    pack_level_info(Level, ITerm, _Format, Def),
  244    Def \== (-),
  245    \+ memberchk(ITerm, Infos).
 pack_info_term(+PackDir, ?Info) is nondet
True when Info is meta-data for the package PackName.
  251pack_info_term(BaseDir, Info) :-
  252    directory_file_path(BaseDir, 'pack.pl', InfoFile),
  253    catch(
  254        term_in_file(valid_term(pack_info_term), InfoFile, Info),
  255        error(existence_error(source_sink, InfoFile), _),
  256        ( print_message(error, pack(no_meta_data(BaseDir))),
  257          fail
  258        )).
  259pack_info_term(BaseDir, library(Lib)) :-
  260    atom_concat(BaseDir, '/prolog/', LibDir),
  261    atom_concat(LibDir, '*.pl', Pattern),
  262    expand_file_name(Pattern, Files),
  263    maplist(atom_concat(LibDir), Plain, Files),
  264    convlist(base_name, Plain, Libs),
  265    member(Lib, Libs),
  266    Lib \== 'INDEX'.
  267pack_info_term(BaseDir, autoload(true)) :-
  268    atom_concat(BaseDir, '/prolog/INDEX.pl', IndexFile),
  269    exists_file(IndexFile).
  270pack_info_term(BaseDir, automatic(Boolean)) :-
  271    once(pack_status_dir(BaseDir, automatic(Boolean))).
  272pack_info_term(BaseDir, built(Arch, Prolog)) :-
  273    pack_status_dir(BaseDir, built(Arch, Prolog, _How)).
  274pack_info_term(BaseDir, link(Dest)) :-
  275    read_link(BaseDir, _, Dest).
  276
  277base_name(File, Base) :-
  278    file_name_extension(Base, pl, File).
 term_in_file(:Valid, +File, -Term) is nondet
True when Term appears in file and call(Valid, Term) is true.
  284:- meta_predicate
  285    term_in_file(1, +, -).  286
  287term_in_file(Valid, File, Term) :-
  288    exists_file(File),
  289    setup_call_cleanup(
  290        open(File, read, In, [encoding(utf8)]),
  291        term_in_stream(Valid, In, Term),
  292        close(In)).
  293
  294term_in_stream(Valid, In, Term) :-
  295    repeat,
  296        read_term(In, Term0, []),
  297        (   Term0 == end_of_file
  298        ->  !, fail
  299        ;   Term = Term0,
  300            call(Valid, Term0)
  301        ).
  302
  303:- meta_predicate
  304    valid_term(1,+).  305
  306valid_term(Type, Term) :-
  307    Term =.. [Name|Args],
  308    same_length(Args, Types),
  309    Decl =.. [Name|Types],
  310    (   call(Type, Decl)
  311    ->  maplist(valid_info_arg, Types, Args)
  312    ;   print_message(warning, pack(invalid_term(Type, Term))),
  313        fail
  314    ).
  315
  316valid_info_arg(Type, Arg) :-
  317    must_be(Type, Arg).
 pack_info_term(?Term) is nondet
True when Term describes name and arguments of a valid package info term.
  324pack_info_term(name(atom)).                     % Synopsis
  325pack_info_term(title(atom)).
  326pack_info_term(keywords(list(atom))).
  327pack_info_term(description(list(atom))).
  328pack_info_term(version(version)).
  329pack_info_term(author(atom, email_or_url_or_empty)).     % Persons
  330pack_info_term(maintainer(atom, email_or_url)).
  331pack_info_term(packager(atom, email_or_url)).
  332pack_info_term(pack_version(nonneg)).           % Package convention version
  333pack_info_term(home(atom)).                     % Home page
  334pack_info_term(download(atom)).                 % Source
  335pack_info_term(provides(atom)).                 % Dependencies
  336pack_info_term(requires(dependency)).
  337pack_info_term(conflicts(dependency)).          % Conflicts with package
  338pack_info_term(replaces(atom)).                 % Replaces another package
  339pack_info_term(autoload(boolean)).              % Default installation options
  340
  341:- multifile
  342    error:has_type/2.  343
  344error:has_type(version, Version) :-
  345    atom(Version),
  346    is_version(Version).
  347error:has_type(email_or_url, Address) :-
  348    atom(Address),
  349    (   sub_atom(Address, _, _, _, @)
  350    ->  true
  351    ;   uri_is_global(Address)
  352    ).
  353error:has_type(email_or_url_or_empty, Address) :-
  354    (   Address == ''
  355    ->  true
  356    ;   error:has_type(email_or_url, Address)
  357    ).
  358error:has_type(dependency, Value) :-
  359    is_dependency(Value).
  360
  361is_version(Version) :-
  362    split_string(Version, ".", "", Parts),
  363    maplist(number_string, _, Parts).
  364
  365is_dependency(Var) :-
  366    var(Var),
  367    !,
  368    fail.
  369is_dependency(Token) :-
  370    atom(Token),
  371    !.
  372is_dependency(Term) :-
  373    compound(Term),
  374    compound_name_arguments(Term, Op, [Token,Version]),
  375    atom(Token),
  376    cmp(Op, _),
  377    is_version(Version),
  378    !.
  379is_dependency(PrologToken) :-
  380    is_prolog_token(PrologToken).
  381
  382cmp(<,  @<).
  383cmp(=<, @=<).
  384cmp(==, ==).
  385cmp(>=, @>=).
  386cmp(>,  @>).
  387
  388
  389                 /*******************************
  390                 *            SEARCH            *
  391                 *******************************/
 pack_list(+Query) is det
 pack_list(+Query, +Options) is det
 pack_search(+Query) is det
Query package server and installed packages and display results. Query is matches case-insensitively against the name and title of known and installed packages. For each matching package, a single line is displayed that provides:

Options processed:

installed(true)
Only list packages that are locally installed. Contacts the server to compare our local version to the latest available version.
outdated(true)
Only list packages that need to be updated. This option implies installed(true).
server((Server|false))
If false, do not contact the server. This implies installed(true). Otherwise, use the given pack server.

Hint: ?- pack_list(''). lists all known packages.

The predicates pack_list/1 and pack_search/1 are synonyms. Both contact the package server at https://www.swi-prolog.org to find available packages. Contacting the server can be avoided using the server(false) option.

  433pack_list(Query) :-
  434    pack_list(Query, []).
  435
  436pack_search(Query) :-
  437    pack_list(Query, []).
  438
  439pack_list(Query, Options) :-
  440    (   option(installed(true), Options)
  441    ;   option(outdated(true), Options)
  442    ;   option(server(false), Options)
  443    ),
  444    !,
  445    local_search(Query, Local),
  446    maplist(arg(1), Local, Packs),
  447    (   option(server(false), Options)
  448    ->  Hits = []
  449    ;   query_pack_server(info(Packs), true(Hits), Options)
  450    ),
  451    list_hits(Hits, Local, Options).
  452pack_list(Query, Options) :-
  453    query_pack_server(search(Query), Result, Options),
  454    (   Result == false
  455    ->  (   local_search(Query, Packs),
  456            Packs \== []
  457        ->  forall(member(pack(Pack, Stat, Title, Version, _), Packs),
  458                   format('~w ~w@~w ~28|- ~w~n',
  459                          [Stat, Pack, Version, Title]))
  460        ;   print_message(warning, pack(search_no_matches(Query)))
  461        )
  462    ;   Result = true(Hits), % Hits = list(pack(Name, p, Title, Version, URL))
  463        local_search(Query, Local),
  464        list_hits(Hits, Local, [])
  465    ).
  466
  467list_hits(Hits, Local, Options) :-
  468    append(Hits, Local, All),
  469    sort(All, Sorted),
  470    join_status(Sorted, Packs0),
  471    include(filtered(Options), Packs0, Packs),
  472    maplist(list_hit(Options), Packs).
  473
  474filtered(Options, pack(_,Tag,_,_,_)) :-
  475    option(outdated(true), Options),
  476    !,
  477    Tag == 'U'.
  478filtered(_, _).
  479
  480list_hit(_Options, pack(Pack, Tag, Title, Version, _URL)) =>
  481    list_tag(Tag),
  482    ansi_format(code, '~w', [Pack]),
  483    format('@'),
  484    list_version(Tag, Version),
  485    format('~35|- ', []),
  486    ansi_format(comment, '~w~n', [Title]).
  487
  488list_tag(Tag) :-
  489    tag_color(Tag, Color),
  490    ansi_format(Color, '~w ', [Tag]).
  491
  492list_version(Tag, VersionI-VersionS) =>
  493    tag_color(Tag, Color),
  494    ansi_format(Color, '~w', [VersionI]),
  495    ansi_format(bold, '(~w)', [VersionS]).
  496list_version(_Tag, Version) =>
  497    ansi_format([], '~w', [Version]).
  498
  499tag_color('U', warning) :- !.
  500tag_color('A', comment) :- !.
  501tag_color(_, []).
 join_status(+PacksIn, -PacksOut) is det
Combine local and remote information to assess the status of each package. PacksOut is a list of pack(Name, Status, Version, URL). If the versions do not match, Version is VersionInstalled-VersionRemote and similar for thee URL.
  510join_status([], []).
  511join_status([ pack(Pack, i, Title, Version, URL),
  512              pack(Pack, p, Title, Version, _)
  513            | T0
  514            ],
  515            [ pack(Pack, Tag, Title, Version, URL)
  516            | T
  517            ]) :-
  518    !,
  519    (   pack_status(Pack, automatic(true))
  520    ->  Tag = a
  521    ;   Tag = i
  522    ),
  523    join_status(T0, T).
  524join_status([ pack(Pack, i, Title, VersionI, URLI),
  525              pack(Pack, p, _,     VersionS, URLS)
  526            | T0
  527            ],
  528            [ pack(Pack, Tag, Title, VersionI-VersionS, URLI-URLS)
  529            | T
  530            ]) :-
  531    !,
  532    version_sort_key(VersionI, VDI),
  533    version_sort_key(VersionS, VDS),
  534    (   VDI @< VDS
  535    ->  Tag = 'U'
  536    ;   Tag = 'A'
  537    ),
  538    join_status(T0, T).
  539join_status([ pack(Pack, i, Title, VersionI, URL)
  540            | T0
  541            ],
  542            [ pack(Pack, l, Title, VersionI, URL)
  543            | T
  544            ]) :-
  545    !,
  546    join_status(T0, T).
  547join_status([H|T0], [H|T]) :-
  548    join_status(T0, T).
 local_search(+Query, -Packs:list(atom)) is det
Search locally installed packs.
  554local_search(Query, Packs) :-
  555    findall(Pack, matching_installed_pack(Query, Pack), Packs).
  556
  557matching_installed_pack(Query, pack(Pack, i, Title, Version, URL)) :-
  558    current_pack(Pack),
  559    findall(Term,
  560            ( pack_info(Pack, _, Term),
  561              search_info(Term)
  562            ), Info),
  563    (   sub_atom_icasechk(Pack, _, Query)
  564    ->  true
  565    ;   memberchk(title(Title), Info),
  566        sub_atom_icasechk(Title, _, Query)
  567    ),
  568    option(title(Title), Info, '<no title>'),
  569    option(version(Version), Info, '<no version>'),
  570    option(download(URL), Info, '<no download url>').
  571
  572search_info(title(_)).
  573search_info(version(_)).
  574search_info(download(_)).
  575
  576
  577                 /*******************************
  578                 *            INSTALL           *
  579                 *******************************/
 pack_install(+Spec:atom) is det
 pack_install(+SpecOrList, +Options) is det
Install one or more packs from SpecOrList. SpecOrList is a single specification or a list of specifications. A specification is one of

Processes the options below. Default options as would be used by pack_install/1 are used to complete the provided Options. Note that pack_install/2 can be used through the SWI-Prolog command line app pack as below. Most of the options of this predicate are available as command line options.

swipl pack install <name>

Options:

url(+URL)
Source for downloading the package
pack_directory(+Dir)
Directory into which to install the package.
global(+Boolean)
If true, install in the XDG common application data path, making the pack accessible to everyone. If false, install in the XDG user application data path, making the pack accessible for the current user only. If the option is absent, use the first existing and writable directory. If that doesn't exist find locations where it can be created and prompt the user to do so.
insecure(+Boolean)
When true (default false), do not perform any checks on SSL certificates when downloading using https.
interactive(+Boolean)
Use default answer without asking the user if there is a default action.
silent(+Boolean)
If true (default false), suppress informational progress messages.
upgrade(+Boolean)
If true (default false), upgrade package if it is already installed.
rebuild(Condition)
Rebuild the foreign components. Condition is one of if_absent (default, do nothing if the directory with foreign resources exists), make (run make) or true (run `make distclean` followed by the default configure and build steps).
test(Boolean)
If true (default), run the pack tests.
git(+Boolean)
If true (default false unless URL ends with .git), assume the URL is a GIT repository.
link(+Boolean)
Can be used if the installation source is a local directory and the file system supports symbolic links. In this case the system adds the current directory to the pack registration using a symbolic link and performs the local installation steps.
version(+Version)
Demand the pack to satisfy some version requirement. Version is as defined by require_version/3. For example '1.5' is the same as >=('1.5').
branch(+Branch)
When installing from a git repository, clone this branch.
commit(+Commit)
When installing from a git repository, checkout this commit. Commit is either a hash, a tag, a branch or 'HEAD'.
build_type(+Type)
When building using CMake, use -DCMAKE_BUILD_TYPE=Type. Default is the build type of Prolog or Release.
register(+Boolean)
If true (default), register packages as downloaded after performing the download. This contacts the server with the meta-data of each pack that was downloaded. The server will either register the location as a new version or increment the download count. The server stores the IP address of the client. Subsequent downloads of the same version from the same IP address are ignored.
server(+URL)
Pack server to contact. Default is the setting prolog_pack:server, by default set to https://www.swi-prolog.org/pack/

Non-interactive installation can be established using the option interactive(false). It is adviced to install from a particular trusted URL instead of the plain pack name for unattented operation.

  679pack_install(Spec) :-
  680    pack_default_options(Spec, Pack, [], Options),
  681    pack_install(Pack, [pack(Pack)|Options]).
  682
  683pack_install(Specs, Options) :-
  684    is_list(Specs),
  685    !,
  686    maplist(pack_options(Options), Specs, Pairs),
  687    pack_install_dir(PackTopDir, Options),
  688    pack_install_set(Pairs, PackTopDir, Options).
  689pack_install(Spec, Options) :-
  690    pack_default_options(Spec, Pack, Options, DefOptions),
  691    (   option(already_installed(Installed), DefOptions)
  692    ->  print_message(informational, pack(already_installed(Installed)))
  693    ;   merge_options(Options, DefOptions, PackOptions),
  694        pack_install_dir(PackTopDir, PackOptions),
  695        pack_install_set([Pack-PackOptions], PackTopDir, Options)
  696    ).
  697
  698pack_options(Options, Spec, Pack-PackOptions) :-
  699    pack_default_options(Spec, Pack, Options, DefOptions),
  700    merge_options(Options, DefOptions, PackOptions).
 pack_default_options(+Spec, -Pack, +OptionsIn, -Options) is det
Establish the pack name (Pack) and install options from a specification and options (OptionsIn) provided by the user. Cases:
  1. Already installed. We must pass that as pack_default_options/4 is called twice from pack_install/2.
  2. Install from a URL due to a url(URL) option. Determine whether the URL is a GIT repository, get the version and pack from the URL.
  3. Install a local archive file. Extract the pack and version from the archive name.
  4. Install from a git URL. Determines the pack, sets git(true) and adds the URL as option.
  5. Install from a directory. Get the info from the packs.pl file.
  6. Install from '.'. Create a symlink to make the current dir accessible as a pack.
  7. Install from a non-git URL Determine pack and version.
  8. Pack name. Query the server to find candidate packs and select an adequate pack.
  726pack_default_options(_Spec, Pack, OptsIn, Options) :-   % (1)
  727    option(already_installed(pack(Pack,_Version)), OptsIn),
  728    !,
  729    Options = OptsIn.
  730pack_default_options(_Spec, Pack, OptsIn, Options) :-   % (2)
  731    option(url(URL), OptsIn),
  732    !,
  733    (   option(git(_), OptsIn)
  734    ->  Options = OptsIn
  735    ;   git_url(URL, Pack, OptsIn)
  736    ->  Options = [git(true)|OptsIn]
  737    ;   Options = OptsIn
  738    ),
  739    (   nonvar(Pack)
  740    ->  true
  741    ;   option(pack(Pack), Options)
  742    ->  true
  743    ;   pack_version_file(Pack, _Version, URL)
  744    ).
  745pack_default_options(Archive, Pack, OptsIn, Options) :- % (3)
  746    must_be(atom, Archive),
  747    \+ uri_is_global(Archive),
  748    expand_file_name(Archive, [File]),
  749    exists_file(File),
  750    !,
  751    (   pack_version_file(Pack, Version, File)
  752    ->  uri_file_name(FileURL, File),
  753        merge_options([url(FileURL), version(Version)], OptsIn, Options)
  754    ;   domain_error(pack_file_name, Archive)
  755    ).
  756pack_default_options(URL, Pack, OptsIn, Options) :-     % (4)
  757    git_url(URL, Pack, OptsIn),
  758    !,
  759    merge_options([git(true), url(URL)], OptsIn, Options).
  760pack_default_options(FileURL, Pack, _, Options) :-      % (5)
  761    uri_file_name(FileURL, Dir),
  762    exists_directory(Dir),
  763    pack_info_term(Dir, name(Pack)),
  764    !,
  765    (   pack_info_term(Dir, version(Version))
  766    ->  uri_file_name(DirURL, Dir),
  767        Options = [url(DirURL), version(Version)]
  768    ;   throw(error(existence_error(key, version, Dir),_))
  769    ).
  770pack_default_options('.', Pack, OptsIn, Options) :-     % (6)
  771    pack_info_term('.', name(Pack)),
  772    !,
  773    working_directory(Dir, Dir),
  774    (   pack_info_term(Dir, version(Version))
  775    ->  uri_file_name(DirURL, Dir),
  776        NewOptions = [url(DirURL), version(Version) | Options1],
  777        (   current_prolog_flag(windows, true)
  778        ->  Options1 = []
  779        ;   Options1 = [link(true), rebuild(make)]
  780        ),
  781        merge_options(NewOptions, OptsIn, Options)
  782    ;   throw(error(existence_error(key, version, Dir),_))
  783    ).
  784pack_default_options(URL, Pack, OptsIn, Options) :-      % (7)
  785    pack_version_file(Pack, Version, URL),
  786    download_url(URL),
  787    !,
  788    available_download_versions(URL, Available, Options),
  789    Available = [URLVersion-LatestURL|_],
  790    NewOptions = [url(LatestURL)|VersionOptions],
  791    version_options(Version, URLVersion, Available, VersionOptions),
  792    merge_options(NewOptions, OptsIn, Options).
  793pack_default_options(Pack, Pack, Options, Options) :-    % (8)
  794    \+ uri_is_global(Pack).
  795
  796version_options(Version, Version, _, [version(Version)]) :- !.
  797version_options(Version, _, Available, [versions(Available)]) :-
  798    sub_atom(Version, _, _, _, *),
  799    !.
  800version_options(_, _, _, []).
 pack_install_dir(-PackDir, +Options) is det
Determine the directory below which to install new packs. This find or creates a writeable directory. Options:

If no writeable directory is found, generate possible location where this directory can be created and ask the user to create one of them.

  820pack_install_dir(PackDir, Options) :-
  821    option(pack_directory(PackDir), Options),
  822    ensure_directory(PackDir),
  823    !.
  824pack_install_dir(PackDir, Options) :-
  825    base_alias(Alias, Options),
  826    absolute_file_name(Alias, PackDir,
  827                       [ file_type(directory),
  828                         access(write),
  829                         file_errors(fail)
  830                       ]),
  831    !.
  832pack_install_dir(PackDir, Options) :-
  833    pack_create_install_dir(PackDir, Options).
  834
  835base_alias(Alias, Options) :-
  836    option(global(true), Options),
  837    !,
  838    Alias = common_app_data(pack).
  839base_alias(Alias, Options) :-
  840    option(global(false), Options),
  841    !,
  842    Alias = user_app_data(pack).
  843base_alias(Alias, _Options) :-
  844    Alias = pack('.').
  845
  846pack_create_install_dir(PackDir, Options) :-
  847    base_alias(Alias, Options),
  848    findall(Candidate = create_dir(Candidate),
  849            ( absolute_file_name(Alias, Candidate, [solutions(all)]),
  850              \+ exists_file(Candidate),
  851              \+ exists_directory(Candidate),
  852              file_directory_name(Candidate, Super),
  853              (   exists_directory(Super)
  854              ->  access_file(Super, write)
  855              ;   true
  856              )
  857            ),
  858            Candidates0),
  859    list_to_set(Candidates0, Candidates),   % keep order
  860    pack_create_install_dir(Candidates, PackDir, Options).
  861
  862pack_create_install_dir(Candidates, PackDir, Options) :-
  863    Candidates = [Default=_|_],
  864    !,
  865    append(Candidates, [cancel=cancel], Menu),
  866    menu(pack(create_pack_dir), Menu, Default, Selected, Options),
  867    Selected \== cancel,
  868    (   catch(make_directory_path(Selected), E,
  869              (print_message(warning, E), fail))
  870    ->  PackDir = Selected
  871    ;   delete(Candidates, PackDir=create_dir(PackDir), Remaining),
  872        pack_create_install_dir(Remaining, PackDir, Options)
  873    ).
  874pack_create_install_dir(_, _, _) :-
  875    print_message(error, pack(cannot_create_dir(pack(.)))),
  876    fail.
 pack_unpack_from_local(+Source, +PackTopDir, +Name, -PackDir, +Options)
Unpack a package from a local media. If Source is a directory, either copy or link the directory. Else, Source must be an archive file. Options:
link(+Boolean)
If the source is a directory, link or copy the directory?
upgrade(true)
If the target is already there, wipe it and make a clean install.
  890pack_unpack_from_local(Source0, PackTopDir, Name, PackDir, Options) :-
  891    exists_directory(Source0),
  892    remove_slash(Source0, Source),
  893    !,
  894    directory_file_path(PackTopDir, Name, PackDir),
  895    (   option(link(true), Options)
  896    ->  (   same_file(Source, PackDir)
  897        ->  true
  898        ;   remove_existing_pack(PackDir, Options),
  899            atom_concat(PackTopDir, '/', PackTopDirS),
  900            relative_file_name(Source, PackTopDirS, RelPath),
  901            link_file(RelPath, PackDir, symbolic),
  902            assertion(same_file(Source, PackDir))
  903        )
  904    ;   \+ option(git(false), Options),
  905        is_git_directory(Source)
  906    ->  remove_existing_pack(PackDir, Options),
  907        run_process(path(git), [clone, '--', Source, PackDir], [])
  908    ;   prepare_pack_dir(PackDir, Options),
  909        copy_directory(Source, PackDir)
  910    ).
  911pack_unpack_from_local(Source, PackTopDir, Name, PackDir, Options) :-
  912    exists_file(Source),
  913    directory_file_path(PackTopDir, Name, PackDir),
  914    prepare_pack_dir(PackDir, Options),
  915    pack_unpack(Source, PackDir, Name, Options).
 pack_unpack(+SourceFile, +PackDir, +Pack, +Options)
Unpack an archive to the given package dir.
To be done
- If library(archive) is not provided we could check for a suitable external program such as tar or unzip.
  924:- if(exists_source(library(archive))).  925pack_unpack(Source, PackDir, Pack, Options) :-
  926    ensure_loaded_archive,
  927    pack_archive_info(Source, Pack, _Info, StripOptions),
  928    prepare_pack_dir(PackDir, Options),
  929    archive_extract(Source, PackDir,
  930                    [ exclude(['._*'])          % MacOS resource forks
  931                    | StripOptions
  932                    ]).
  933:- else.  934pack_unpack(_,_,_,_) :-
  935    existence_error(library, archive).
  936:- endif.
 pack_install_local(:Spec, +Dir, +Options) is det
Install a number of packages in a local directory. This predicate supports installing packages local to an application rather than globally.
  944pack_install_local(M:Gen, Dir, Options) :-
  945    findall(Pack-PackOptions, call(M:Gen, Pack, PackOptions), Pairs),
  946    pack_install_set(Pairs, Dir, Options).
  947
  948pack_install_set(Pairs, Dir, Options) :-
  949    must_be(list(pair), Pairs),
  950    ensure_directory(Dir),
  951    partition(known_media, Pairs, Local, Remote),
  952    maplist(pack_options_to_versions, Local, LocalVersions),
  953    (   Remote == []
  954    ->  AllVersions = LocalVersions
  955    ;   pairs_keys(Remote, Packs),
  956        prolog_description(Properties),
  957        query_pack_server(versions(Packs, Properties), Result, Options),
  958        (   Result = true(RemoteVersions)
  959        ->  append(LocalVersions, RemoteVersions, AllVersions)
  960        ;   print_message(error, pack(query_failed(Result))),
  961            fail
  962        )
  963    ),
  964    local_packs(Dir, Existing),
  965    pack_resolve(Pairs, Existing, AllVersions, Plan0, Options),
  966    !,                                      % for now, only first plan
  967    maplist(hsts_info(Options), Plan0, Plan),
  968    Options1 = [pack_directory(Dir), installed_packs(Existing)|Options],
  969    download_plan(Pairs, Plan, PlanB, Options1),
  970    register_downloads(PlanB, Options),
  971    maplist(update_automatic, PlanB),
  972    build_plan(PlanB, Built, Options1),
  973    publish_download(PlanB, Options),
  974    work_done(Pairs, Plan, PlanB, Built, Options).
  975
  976hsts_info(Options, Info0, Info) :-
  977    hsts(Info0.get(url), URL, Options),
  978    !,
  979    Info = Info0.put(url, URL).
  980hsts_info(_Options, Info, Info).
 known_media(+Pair) is semidet
True when the options specify installation from a known media. If that applies to all packs, there is no need to query the server. We first download and unpack the known media, then examine the requirements and, if necessary, go to the server to resolve these.
  989known_media(_-Options) :-
  990    option(url(_), Options).
 pack_resolve(+Pairs, +Existing, +Versions, -Plan, +Options) is det
Generate an installation plan. Pairs is a list of Pack-Options pairs that specifies the desired packages. Existing is a list of pack(Pack, i, Title, Version, URL) terms that represents the already installed packages. Versions is obtained from the server. See pack.pl from the web server for details. On success, this results in a Plan to satisfies the requirements. The plan is a list of packages to install with their location. The steps satisfy the partial ordering of dependencies, such that dependencies are installed before the dependents. Options:
upgrade(true)
When specified, we try to install the latest version of all the packages. Otherwise, we try to minimise the installation.
 1008pack_resolve(Pairs, Existing, Versions, Plan, Options) :-
 1009    insert_existing(Existing, Versions, AllVersions, Options),
 1010    phrase(select_version(Pairs, AllVersions,
 1011                          [ plan(PlanA),           % access to plan
 1012                            dependency_for([])     % dependencies
 1013                          | Options
 1014                          ]),
 1015           PlanA),
 1016    mark_installed(PlanA, Existing, Plan).
 insert_existing(+Existing, +Available, -Candidates, +Options) is det
Combine the already existing packages with the ones reported as available by the server to a list of Candidates, where the candidate of each package is ordered according by preference. When upgrade(true) is specified, the existing is merged into the set of Available versions. Otherwise Existing is prepended to Available, so it is selected as first.
 1027:- det(insert_existing/4). 1028insert_existing(Existing, [], Versions, _Options) =>
 1029    maplist(existing_to_versions, Existing, Versions).
 1030insert_existing(Existing, [Pack-Versions|T0], AllPackVersions, Options),
 1031    select(Installed, Existing, Existing2),
 1032    Installed.pack == Pack =>
 1033    can_upgrade(Installed, Versions, Installed2),
 1034    insert_existing_(Installed2, Versions, AllVersions, Options),
 1035    AllPackVersions = [Pack-AllVersions|T],
 1036    insert_existing(Existing2, T0, T, Options).
 1037insert_existing(Existing, [H|T0], AllVersions, Options) =>
 1038    AllVersions = [H|T],
 1039    insert_existing(Existing, T0, T, Options).
 1040
 1041existing_to_versions(Installed, Pack-[Version-[Installed]]) :-
 1042    Pack = Installed.pack,
 1043    Version = Installed.version.
 1044
 1045insert_existing_(Installed, Versions, AllVersions, Options) :-
 1046    option(upgrade(true), Options),
 1047    !,
 1048    insert_existing_(Installed, Versions, AllVersions).
 1049insert_existing_(Installed, Versions, AllVersions, _) :-
 1050    AllVersions = [Installed.version-[Installed]|Versions].
 1051
 1052insert_existing_(Installed, [H|T0], [H|T]) :-
 1053    H = V0-_Infos,
 1054    cmp_versions(>, V0, Installed.version),
 1055    !,
 1056    insert_existing_(Installed, T0, T).
 1057insert_existing_(Installed, [H0|T], [H|T]) :-
 1058    H0 = V0-Infos,
 1059    V0 == Installed.version,
 1060    !,
 1061    H = V0-[Installed|Infos].
 1062insert_existing_(Installed, Versions, All) :-
 1063    All =  [Installed.version-[Installed]|Versions].
 can_upgrade(+Installed, +Versions, -Installed2) is det
Add a latest_version key to Installed if its version is older than the latest available version.
 1070can_upgrade(Info, [Version-_|_], Info2) :-
 1071    cmp_versions(>, Version, Info.version),
 1072    !,
 1073    Info2 = Info.put(latest_version, Version).
 1074can_upgrade(Info, _, Info).
 mark_installed(+PlanA, +Existing, -Plan) is det
Mark already up-to-date packs from the plan and add a key upgrade:true to elements of PlanA in Existing that are not the same.
 1082mark_installed([], _, []).
 1083mark_installed([Info|T], Existing, Plan) :-
 1084    (   member(Installed, Existing),
 1085        Installed.pack == Info.pack
 1086    ->  (   (   Installed.git == true
 1087            ->  Info.git == true,
 1088                Installed.hash == Info.hash
 1089            ;   Version = Info.get(version)
 1090            ->  Installed.version == Version
 1091            )
 1092        ->  Plan = [Info.put(keep, true)|PlanT]    % up-to-date
 1093        ;   Plan = [Info.put(upgrade, Installed)|PlanT] % needs upgrade
 1094        )
 1095    ;   Plan = [Info|PlanT]                        % new install
 1096    ),
 1097    mark_installed(T, Existing, PlanT).
 select_version(+PackAndOptions, +Available, +Options)// is nondet
True when the output is a list of pack info dicts that satisfy the installation requirements of PackAndOptions from the packs known to be Available.
 1105select_version([], _, _) -->
 1106    [].
 1107select_version([Pack-PackOptions|More], Versions, Options) -->
 1108    { memberchk(Pack-PackVersions, Versions),
 1109      member(Version-Infos, PackVersions),
 1110      compatible_version(Pack, Version, PackOptions),
 1111      member(Info, Infos),
 1112      pack_options_compatible_with_info(Info, PackOptions),
 1113      pack_satisfies(Pack, Version, Info, Info2, PackOptions),
 1114      all_downloads(PackVersions, Downloads)
 1115    },
 1116    add_to_plan(Info2.put(_{version: Version, all_downloads:Downloads}),
 1117                Versions, Options),
 1118    select_version(More, Versions, Options).
 1119select_version([Pack-_PackOptions|_More], _Versions, _Options) -->
 1120    { existence_error(pack, Pack) }.               % or warn and continue?
 1121
 1122all_downloads(PackVersions, AllDownloads) :-
 1123    aggregate_all(sum(Downloads),
 1124                  ( member(_Version-Infos, PackVersions),
 1125                    member(Info, Infos),
 1126                    get_dict(downloads, Info, Downloads)
 1127                  ),
 1128                  AllDownloads).
 1129
 1130add_requirements([], _, _) -->
 1131    [].
 1132add_requirements([H|T], Versions, Options) -->
 1133    { is_prolog_token(H),
 1134      !,
 1135      prolog_satisfies(H)
 1136    },
 1137    add_requirements(T, Versions, Options).
 1138add_requirements([H|T], Versions, Options) -->
 1139    { member(Pack-PackVersions, Versions),
 1140      member(Version-Infos, PackVersions),
 1141      member(Info, Infos),
 1142      (   Provides = @(Pack,Version)
 1143      ;   member(Provides, Info.get(provides))
 1144      ),
 1145      satisfies_req(Provides, H),
 1146      all_downloads(PackVersions, Downloads)
 1147    },
 1148    add_to_plan(Info.put(_{version: Version, all_downloads:Downloads}),
 1149                Versions, Options),
 1150    add_requirements(T, Versions, Options).
 add_to_plan(+Info, +Versions, +Options) is semidet
Add Info to the plan. If an Info about the same pack is already in the plan, but this is a different version of the pack, we must fail as we cannot install two different versions of a pack.
 1158add_to_plan(Info, _Versions, Options) -->
 1159    { option(plan(Plan), Options),
 1160      member_nonvar(Planned, Plan),
 1161      Planned.pack == Info.pack,
 1162      !,
 1163      same_version(Planned, Info)                  % same pack, different version
 1164    }.
 1165add_to_plan(Info, _Versions, _Options) -->
 1166    { member(Conflict, Info.get(conflicts)),
 1167      is_prolog_token(Conflict),
 1168      prolog_satisfies(Conflict),
 1169      !,
 1170      fail                                         % incompatible with this Prolog
 1171    }.
 1172add_to_plan(Info, _Versions, Options) -->
 1173    { option(plan(Plan), Options),
 1174      member_nonvar(Planned, Plan),
 1175      info_conflicts(Info, Planned),               % Conflicts with a planned pack
 1176      !,
 1177      fail
 1178    }.
 1179add_to_plan(Info, Versions, Options) -->
 1180    { select_option(dependency_for(Dep0), Options, Options1),
 1181      Options2 = [dependency_for([Info.pack|Dep0])|Options1],
 1182      (   Dep0 = [DepFor|_]
 1183      ->  add_dependency_for(DepFor, Info, Info1)
 1184      ;   Info1 = Info
 1185      )
 1186    },
 1187    [Info1],
 1188    add_requirements(Info.get(requires,[]), Versions, Options2).
 1189
 1190add_dependency_for(Pack, Info, Info) :-
 1191    Old = Info.get(dependency_for),
 1192    !,
 1193    b_set_dict(dependency_for, Info, [Pack|Old]).
 1194add_dependency_for(Pack, Info0, Info) :-
 1195    Info = Info0.put(dependency_for, [Pack]).
 1196
 1197same_version(Info, Info) :-
 1198    !.
 1199same_version(Planned, Info) :-
 1200    Hash = Planned.get(hash),
 1201    Hash \== (-),
 1202    !,
 1203    Hash == Info.get(hash).
 1204same_version(Planned, Info) :-
 1205    Planned.get(version) == Info.get(version).
 info_conflicts(+Info1, +Info2) is semidet
True if Info2 is in conflict with Info2. The relation is symetric.
 1211info_conflicts(Info, Planned) :-
 1212    info_conflicts_(Info, Planned),
 1213    !.
 1214info_conflicts(Info, Planned) :-
 1215    info_conflicts_(Planned, Info),
 1216    !.
 1217
 1218info_conflicts_(Info, Planned) :-
 1219    member(Conflict, Info.get(conflicts)),
 1220    \+ is_prolog_token(Conflict),
 1221    info_provides(Planned, Provides),
 1222    satisfies_req(Provides, Conflict),
 1223    !.
 1224
 1225info_provides(Info, Provides) :-
 1226    (   Provides = Info.pack@Info.version
 1227    ;   member(Provides, Info.get(provides))
 1228    ).
 pack_satisfies(+Pack, +Version, +Info0, -Info, +Options) is semidet
True if Pack@Version with Info satisfies the pack installation options provided by Options.
 1235pack_satisfies(_Pack, _Version, Info0, Info, Options) :-
 1236    option(commit('HEAD'), Options),
 1237    !,
 1238    Info0.get(git) == true,
 1239    Info = Info0.put(commit, 'HEAD').
 1240pack_satisfies(_Pack, _Version, Info, Info, Options) :-
 1241    option(commit(Commit), Options),
 1242    !,
 1243    Commit == Info.get(hash).
 1244pack_satisfies(Pack, Version, Info, Info, Options) :-
 1245    option(version(ReqVersion), Options),
 1246    !,
 1247    satisfies_version(Pack, Version, ReqVersion).
 1248pack_satisfies(_Pack, _Version, Info, Info, _Options).
 satisfies_version(+Pack, +PackVersion, +RequiredVersion) is semidet
 1252satisfies_version(Pack, Version, ReqVersion) :-
 1253    catch(require_version(pack(Pack), Version, ReqVersion),
 1254          error(version_error(pack(Pack), Version, ReqVersion),_),
 1255          fail).
 satisfies_req(+Provides, +Required) is semidet
Check a token requirements.
 1261satisfies_req(Token, Token) => true.
 1262satisfies_req(@(Token,_), Token) => true.
 1263satisfies_req(@(Token,PrvVersion), Req), cmp(Req, Token, Cmp, ReqVersion) =>
 1264	cmp_versions(Cmp, PrvVersion, ReqVersion).
 1265satisfies_req(_,_) => fail.
 1266
 1267cmp(Token  < Version, Token, <,	 Version).
 1268cmp(Token =< Version, Token, =<, Version).
 1269cmp(Token =  Version, Token, =,	 Version).
 1270cmp(Token == Version, Token, ==, Version).
 1271cmp(Token >= Version, Token, >=, Version).
 1272cmp(Token >  Version, Token, >,	 Version).
 pack_options_to_versions(+PackOptionsPair, -Versions) is det
Create an available package term from Pack and Options if it contains a url(URL) option. This allows installing packages that are not known to the server. In most cases, the URL will be a git URL or the URL to download an archive. It can also be a file:// url to install from a local archive.

The first clause deals with a wildcard URL. See pack_default_options/4, case (7).

 1285:- det(pack_options_to_versions/2). 1286pack_options_to_versions(Pack-PackOptions, Pack-Versions) :-
 1287    option(versions(Available), PackOptions), !,
 1288    maplist(version_url_info(Pack, PackOptions), Available, Versions).
 1289pack_options_to_versions(Pack-PackOptions, Pack-[Version-[Info]]) :-
 1290    option(url(URL), PackOptions),
 1291    findall(Prop, option_info_prop(PackOptions, Prop), Pairs),
 1292    dict_create(Info, #,
 1293                [ pack-Pack,
 1294                  url-URL
 1295                | Pairs
 1296                ]),
 1297    Version = Info.get(version, '0.0.0').
 1298
 1299version_url_info(Pack, PackOptions, Version-URL, Version-[Info]) :-
 1300    findall(Prop,
 1301            ( option_info_prop(PackOptions, Prop),
 1302              Prop \= version-_
 1303            ),
 1304            Pairs),
 1305    dict_create(Info, #,
 1306                [ pack-Pack,
 1307                  url-URL,
 1308                  version-Version
 1309                | Pairs
 1310                ]).
 1311
 1312option_info_prop(PackOptions, Prop-Value) :-
 1313    option_info(Prop),
 1314    Opt =.. [Prop,Value],
 1315    option(Opt, PackOptions).
 1316
 1317option_info(git).
 1318option_info(hash).
 1319option_info(version).
 1320option_info(branch).
 1321option_info(link).
 compatible_version(+Pack, +Version, +Options) is semidet
Fails if Options demands a version and Version is not compatible with Version.
 1328compatible_version(Pack, Version, PackOptions) :-
 1329    option(version(ReqVersion), PackOptions),
 1330    !,
 1331    satisfies_version(Pack, Version, ReqVersion).
 1332compatible_version(_, _, _).
 pack_options_compatible_with_info(+Info, +PackOptions) is semidet
Ignore information from the server that is incompatible with the request.
 1339pack_options_compatible_with_info(Info, PackOptions) :-
 1340    findall(Prop, option_info_prop(PackOptions, Prop), Pairs),
 1341    dict_create(Dict, _, Pairs),
 1342    Dict >:< Info.
 download_plan(+Targets, +Plan, +Options) is semidet
Download or update all packages from Plan. We need to do this as a first step because we may not have (up-to-date) dependency information about all packs. For example, a pack may be installed at the git HEAD revision that is not yet known to the server or it may be installed from a url that is not known at all at the server.
 1352download_plan(_Targets, Plan, Plan, _Options) :-
 1353    exclude(installed, Plan, []),
 1354    !.
 1355download_plan(Targets, Plan0, Plan, Options) :-
 1356    confirm(download_plan(Plan0), yes, Options),
 1357    maplist(download_from_info(Options), Plan0, Plan1),
 1358    plan_unsatisfied_dependencies(Plan1, Deps),
 1359    (   Deps == []
 1360    ->  Plan = Plan1
 1361    ;   print_message(informational, pack(new_dependencies(Deps))),
 1362        prolog_description(Properties),
 1363        query_pack_server(versions(Deps, Properties), Result, []),
 1364        (   Result = true(Versions)
 1365        ->  merge_installed(Plan1, Options, Existing),
 1366            pack_resolve(Targets, Existing, Versions, Plan2, Options),
 1367            !,
 1368            download_plan(Targets, Plan2, Plan, Options)
 1369        ;   print_message(error, pack(query_failed(Result))),
 1370            fail
 1371        )
 1372    ).
 merge_installed(+Plan, +Options, -Existing) is det
Combine the just-processed Plan with the locally installed packs passed through Options as installed_packs(Installed), so that the recursive dependency resolution considers already installed packs able to satisfy requirements. Packs in Plan shadow same pack in Installed.
 1382merge_installed(Plan, Options, Existing) :-
 1383    option(installed_packs(Installed), Options, []),
 1384    exclude(in_plan(Plan), Installed, InstalledRest),
 1385    append(Plan, InstalledRest, Existing).
 1386
 1387in_plan(Plan, Info) :-
 1388    member(P, Plan),
 1389    P.pack == Info.pack,
 1390    !.
 plan_unsatisfied_dependencies(+Plan, -Deps) is det
True when Deps is a list of dependency tokens in Plan that is not satisfied.
 1397plan_unsatisfied_dependencies(Plan, Deps) :-
 1398    phrase(plan_unsatisfied_dependencies(Plan, Plan), Deps).
 1399
 1400plan_unsatisfied_dependencies([], _) -->
 1401    [].
 1402plan_unsatisfied_dependencies([Info|Infos], Plan) -->
 1403    { Deps = Info.get(requires) },
 1404    plan_unsatisfied_requirements(Deps, Plan),
 1405    plan_unsatisfied_dependencies(Infos, Plan).
 1406
 1407plan_unsatisfied_requirements([], _) -->
 1408    [].
 1409plan_unsatisfied_requirements([H|T], Plan) -->
 1410    { is_prolog_token(H),           % Can this fail?
 1411      prolog_satisfies(H)
 1412    },
 1413    !,
 1414    plan_unsatisfied_requirements(T, Plan).
 1415plan_unsatisfied_requirements([H|T], Plan) -->
 1416    { member(Info, Plan),
 1417      (   (   Version = Info.get(version)
 1418          ->  Provides = @(Info.get(pack), Version)
 1419          ;   Provides = Info.get(pack)
 1420          )
 1421      ;   member(Provides, Info.get(provides))
 1422      ),
 1423      satisfies_req(Provides, H)
 1424    }, !,
 1425    plan_unsatisfied_requirements(T, Plan).
 1426plan_unsatisfied_requirements([H|T], Plan) -->
 1427    [H],
 1428    plan_unsatisfied_requirements(T, Plan).
 build_plan(+Plan, -Built, +Options) is det
Run post installation steps. We build dependencies before their dependents, so we first do a topological sort on the packs based on the pack dependencies.
 1437build_plan(Plan, Ordered, Options) :-
 1438    maplist(decide_autoload_pack(Options), Plan, Plan1),
 1439    partition(needs_rebuild_from_info(Options), Plan1, ToBuild, NoBuild),
 1440    maplist(attach_from_info(Options), NoBuild),
 1441    (   ToBuild == []
 1442    ->  post_install_autoload(NoBuild),
 1443        Ordered = []
 1444    ;   order_builds(ToBuild, Ordered),
 1445        confirm(build_plan(Ordered), yes, Options),
 1446        maplist(exec_plan_rebuild_step(Options), Ordered)
 1447    ).
 needs_rebuild_from_info(+Options, +Info) is semidet
True when we need to rebuilt the pack.
 1453needs_rebuild_from_info(Options, Info) :-
 1454    PackDir = Info.installed,
 1455    is_foreign_pack(PackDir, _),
 1456    \+ is_built(PackDir, Options).
 is_built(+PackDir, +Options) is semidet
True if the pack in PackDir has been built.
To be done
- We now verify it was built by the exact same version. That is normally an overkill.
 1465is_built(PackDir, _Options) :-
 1466    current_prolog_flag(arch, Arch),
 1467    prolog_version_dotted(Version), % Major.Minor.Patch
 1468    pack_status_dir(PackDir, built(Arch, Version, _)).
 order_builds(+ToBuild, -Ordered) is det
Order the build processes by building dependencies before the packages that rely on them as they may need them during the build.
 1475order_builds(ToBuild, Ordered) :-
 1476    findall(Pack-Dependent, dep_edge(ToBuild, Pack, Dependent), Edges),
 1477    maplist(get_dict(pack), ToBuild, Packs),
 1478    vertices_edges_to_ugraph(Packs, Edges, Graph),
 1479    ugraph_layers(Graph, Layers),
 1480    append(Layers, PackNames),
 1481    maplist(pack_info_from_name(ToBuild), PackNames, Ordered).
 dep_edge(+Infos, -Pack, -Dependent) is nondet
True when Pack needs to be installed as a dependency of Dependent. Both Pack and Dependent are pack names. I.e., this implies that we must build Pack before Dependent.
 1489dep_edge(Infos, Pack, Dependent) :-
 1490    member(Info, Infos),
 1491    Pack = Info.pack,
 1492    member(Dependent, Info.get(dependency_for)),
 1493    (   member(DepInfo, Infos),
 1494        DepInfo.pack == Dependent
 1495    ->  true
 1496    ).
 1497
 1498:- det(pack_info_from_name/3). 1499pack_info_from_name(Infos, Pack, Info) :-
 1500    member(Info, Infos),
 1501    Info.pack == Pack,
 1502    !.
 exec_plan_rebuild_step(+Options, +Info) is det
Execute the rebuild steps for the given Info.
 1508exec_plan_rebuild_step(Options, Info) :-
 1509    print_message(informational, pack(build(Info.pack, Info.installed))),
 1510    pack_post_install(Info, Options),
 1511    attach_from_info(Options, Info).
 attach_from_info(+Options, +Info) is det
Make the package visible.
 1517attach_from_info(_Options, Info) :-
 1518    Info.get(keep) == true,
 1519    !.
 1520attach_from_info(Options, Info) :-
 1521    (   option(pack_directory(_Parent), Options)
 1522    ->  pack_attach(Info.installed, [duplicate(replace)])
 1523    ;   pack_attach(Info.installed, [])
 1524    ).
 download_from_info(+Options, +Info0, -Info) is det
Download a package guided by Info. Note that this does not run any scripts. This implies that dependencies do not matter and we can proceed in any order. This is important because we may use packages at their git HEAD, which implies that requirements may be different from what is in the Info terms.
 1534download_from_info(Options, Info0, Info), option(dryrun(true), Options) =>
 1535    print_term(Info0, [nl(true)]),
 1536    Info = Info0.
 1537download_from_info(_Options, Info0, Info), installed(Info0) =>
 1538    Info = Info0.
 1539download_from_info(_Options, Info0, Info),
 1540    _{upgrade:OldInfo, git:true} :< Info0,
 1541    is_git_directory(OldInfo.installed) =>
 1542    PackDir = OldInfo.installed,
 1543    git_checkout_version(PackDir, [commit(Info0.hash)]),
 1544    reload_info(PackDir, Info0, Info).
 1545download_from_info(Options, Info0, Info),
 1546    _{upgrade:OldInfo} :< Info0 =>
 1547    PackDir = OldInfo.installed,
 1548    detach_pack(OldInfo.pack, PackDir),
 1549    delete_directory_and_contents(PackDir),
 1550    del_dict(upgrade, Info0, _, Info1),
 1551    download_from_info(Options, Info1, Info).
 1552download_from_info(Options, Info0, Info),
 1553    _{url:URL, git:true} :< Info0, \+ have_git =>
 1554    git_archive_url(URL, Archive, Options),
 1555    download_from_info([git_url(URL)|Options],
 1556                       Info0.put(_{ url:Archive,
 1557                                    git:false,
 1558                                    git_url:URL
 1559                                  }),
 1560                       Info1),
 1561                                % restore the hash to register the download.
 1562    (   Info1.get(version) == Info0.get(version),
 1563        Hash = Info0.get(hash)
 1564    ->  Info = Info1.put(hash, Hash)
 1565    ;   Info = Info1
 1566    ).
 1567download_from_info(Options, Info0, Info),
 1568    _{url:URL} :< Info0 =>
 1569    select_option(pack_directory(Dir), Options, Options1),
 1570    select_option(version(_), Options1, Options2, _),
 1571    download_info_extra(Info0, InstallOptions, Options2),
 1572    option(interactive(Interactive), Options, true),
 1573    pack_download_from_url(URL, Dir, Info0.pack,
 1574                           [ interactive(false),
 1575                             confirm_hash(Interactive),
 1576                             pack_dir(PackDir)
 1577                           | InstallOptions
 1578                           ]),
 1579    reload_info(PackDir, Info0, Info).
 1580
 1581download_info_extra(Info, [git(true),commit(Hash)|Options], Options) :-
 1582    Info.get(git) == true,
 1583    !,
 1584    Hash = Info.get(commit, 'HEAD').
 1585download_info_extra(Info, [link(true)|Options], Options) :-
 1586    Info.get(link) == true,
 1587    !.
 1588download_info_extra(Info, [hash(Hash)|Options], Options) :-
 1589    Hash = Info.get(hash),
 1590    is_sha1(Hash),
 1591    !.
 1592download_info_extra(_, Options, Options).
 1593
 1594installed(Info) :-
 1595    _ = Info.get(installed).
 1596
 1597detach_pack(Pack, PackDir) :-
 1598    (   current_pack(Pack, PackDir)
 1599    ->  '$pack_detach'(Pack, PackDir)
 1600    ;   true
 1601    ).
 reload_info(+PackDir, +Info0, -Info) is det
Update the requires and provides metadata. Info0 is what we got from the server, but the package may be different as we may have asked for the git HEAD or the package URL may not have been known by the server at all.
 1610reload_info(_PackDir, Info, Info) :-
 1611    _ = Info.get(installed),	% we read it from the package
 1612    !.
 1613reload_info(PackDir, Info0, Info) :-
 1614    local_pack_info(PackDir, Info1),
 1615    Info = Info0.put(installed, PackDir)
 1616                .put(downloaded, Info0.url)
 1617                .put(Info1).
 work_done(+Targets, +Plan, +PlanB, +Built, +Options) is det
Targets has successfully been installed and the packs Built have successfully ran their build scripts.
 1624work_done(_, _, _, _, Options),
 1625    option(silent(true), Options) =>
 1626    true.
 1627work_done(Targets, Plan, Plan, [], _Options) =>
 1628    convlist(can_upgrade_target(Plan), Targets, CanUpgrade),
 1629    (   CanUpgrade == []
 1630    ->  pairs_keys(Targets, Packs),
 1631        print_message(informational, pack(up_to_date(Packs)))
 1632    ;   print_message(informational, pack(installed_can_upgrade(CanUpgrade)))
 1633    ).
 1634work_done(_, _, _, _, _) =>
 1635    true.
 1636
 1637can_upgrade_target(Plan, Pack-_, Info) =>
 1638    member(Info, Plan),
 1639    Info.pack == Pack,
 1640    !,
 1641    _ = Info.get(latest_version).
 local_packs(+Dir, -Packs) is det
True when Packs is a list with information for all installed packages.
 1648local_packs(Dir, Packs) :-
 1649    findall(Pack, pack_in_subdir(Dir, Pack), Packs).
 1650
 1651pack_in_subdir(Dir, Info) :-
 1652    directory_member(Dir, PackDir,
 1653                     [ file_type(directory),
 1654                       hidden(false)
 1655                     ]),
 1656    local_pack_info(PackDir, Info).
 1657
 1658local_pack_info(PackDir,
 1659                #{ pack: Pack,
 1660                   version: Version,
 1661                   title: Title,
 1662                   hash: Hash,
 1663                   url: URL,
 1664                   git: IsGit,
 1665                   requires: Requires,
 1666                   provides: Provides,
 1667                   conflicts: Conflicts,
 1668                   installed: PackDir
 1669                 }) :-
 1670    directory_file_path(PackDir, 'pack.pl', MetaFile),
 1671    exists_file(MetaFile),
 1672    file_base_name(PackDir, DirName),
 1673    findall(Term, pack_dir_info(PackDir, _, Term), Info),
 1674    option(pack(Pack), Info, DirName),
 1675    option(title(Title), Info, '<no title>'),
 1676    option(version(Version), Info, '<no version>'),
 1677    option(download(URL), Info, '<no download url>'),
 1678    findall(Req, member(requires(Req), Info), Requires),
 1679    findall(Prv, member(provides(Prv), Info), Provides),
 1680    findall(Cfl, member(conflicts(Cfl), Info), Conflicts),
 1681    (   have_git,
 1682        is_git_directory(PackDir)
 1683    ->  git_hash(Hash, [directory(PackDir)]),
 1684        IsGit = true
 1685    ;   Hash = '-',
 1686        IsGit = false
 1687    ).
 1688
 1689
 1690		 /*******************************
 1691		 *        PROLOG VERSIONS	*
 1692		 *******************************/
 prolog_description(-Description) is det
Provide a description of the running Prolog system. Version terms:
To be done
- : establish a language for features. Sync with library(prolog_versions)
 1703prolog_description([prolog(swi(Version))]) :-
 1704    prolog_version(Version).
 1705
 1706prolog_version(Version) :-
 1707    current_prolog_flag(version_git, Version),
 1708    !.
 1709prolog_version(Version) :-
 1710    prolog_version_dotted(Version).
 1711
 1712prolog_version_dotted(Version) :-
 1713    current_prolog_flag(version_data, swi(Major, Minor, Patch, _)),
 1714    VNumbers = [Major, Minor, Patch],
 1715    atomic_list_concat(VNumbers, '.', Version).
 is_prolog_token(+Token) is semidet
True when Token describes a property of the target Prolog system.
 1722is_prolog_token(Token), cmp(Token, prolog, _Cmp, _Version) => true.
 1723is_prolog_token(prolog:Feature), atom(Feature) => true.
 1724is_prolog_token(prolog:Feature), flag_value_feature(Feature, _Flag, _Value) =>
 1725    true.
 1726is_prolog_token(_) => fail.
 prolog_satisfies(+Token) is semidet
True when the running Prolog system satisfies token. Processes requires(Token) terms for
See also
- require_prolog_version/2.
 1741prolog_satisfies(Token), cmp(Token, prolog, Cmp, ReqVersion) =>
 1742    prolog_version(CurrentVersion),
 1743    cmp_versions(Cmp, CurrentVersion, ReqVersion).
 1744prolog_satisfies(prolog:library(Lib)), atom(Lib) =>
 1745    exists_source(library(Lib)).
 1746prolog_satisfies(prolog:Feature), atom(Feature) =>
 1747    current_prolog_flag(Feature, true).
 1748prolog_satisfies(prolog:Feature), flag_value_feature(Feature, Flag, Value) =>
 1749    current_prolog_flag(Flag, Value).
 1750
 1751flag_value_feature(Feature, Flag, Value) :-
 1752    compound(Feature),
 1753    compound_name_arguments(Feature, Flag, [Value]),
 1754    atom(Flag).
 1755
 1756
 1757                 /*******************************
 1758                 *             INFO             *
 1759                 *******************************/
 pack_archive_info(+Archive, +Pack, -Info, -Strip)
True when Archive archives Pack. Info is unified with the terms from pack.pl in the pack and Strip is the strip-option for archive_extract/3.

Requires library(archive), which is lazily loaded when needed.

Errors
- existence_error(pack_file, 'pack.pl') if the archive doesn't contain pack.pl
- Syntax errors if pack.pl cannot be parsed.
 1773:- if(exists_source(library(archive))). 1774ensure_loaded_archive :-
 1775    current_predicate(archive_open/3),
 1776    !.
 1777ensure_loaded_archive :-
 1778    use_module(library(archive)).
 1779
 1780pack_archive_info(Archive, Pack, [archive_size(Bytes)|Info], Strip) :-
 1781    ensure_loaded_archive,
 1782    size_file(Archive, Bytes),
 1783    setup_call_cleanup(
 1784        archive_open(Archive, Handle, []),
 1785        (   repeat,
 1786            (   archive_next_header(Handle, InfoFile)
 1787            ->  true
 1788            ;   !, fail
 1789            )
 1790        ),
 1791        archive_close(Handle)),
 1792    file_base_name(InfoFile, 'pack.pl'),
 1793    atom_concat(Prefix, 'pack.pl', InfoFile),
 1794    strip_option(Prefix, Pack, Strip),
 1795    setup_call_cleanup(
 1796        archive_open_entry(Handle, Stream),
 1797        read_stream_to_terms(Stream, Info),
 1798        close(Stream)),
 1799    !,
 1800    must_be(ground, Info),
 1801    maplist(valid_term(pack_info_term), Info).
 1802:- else. 1803pack_archive_info(_, _, _, _) :-
 1804    existence_error(library, archive).
 1805:- endif. 1806pack_archive_info(_, _, _, _) :-
 1807    existence_error(pack_file, 'pack.pl').
 1808
 1809strip_option('', _, []) :- !.
 1810strip_option('./', _, []) :- !.
 1811strip_option(Prefix, Pack, [remove_prefix(Prefix)]) :-
 1812    atom_concat(PrefixDir, /, Prefix),
 1813    file_base_name(PrefixDir, Base),
 1814    (   Base == Pack
 1815    ->  true
 1816    ;   pack_version_file(Pack, _, Base)
 1817    ->  true
 1818    ;   \+ sub_atom(PrefixDir, _, _, _, /)
 1819    ).
 1820
 1821read_stream_to_terms(Stream, Terms) :-
 1822    read(Stream, Term0),
 1823    read_stream_to_terms(Term0, Stream, Terms).
 1824
 1825read_stream_to_terms(end_of_file, _, []) :- !.
 1826read_stream_to_terms(Term0, Stream, [Term0|Terms]) :-
 1827    read(Stream, Term1),
 1828    read_stream_to_terms(Term1, Stream, Terms).
 pack_git_info(+GitDir, -Hash, -Info) is det
Retrieve info from a cloned git repository that is compatible with pack_archive_info/4.
 1836pack_git_info(GitDir, Hash, [git(true), installed_size(Bytes)|Info]) :-
 1837    exists_directory(GitDir),
 1838    !,
 1839    git_ls_tree(Entries, [directory(GitDir)]),
 1840    git_hash(Hash, [directory(GitDir)]),
 1841    maplist(arg(4), Entries, Sizes),
 1842    sum_list(Sizes, Bytes),
 1843    dir_metadata(GitDir, Info).
 1844
 1845dir_metadata(GitDir, Info) :-
 1846    directory_file_path(GitDir, 'pack.pl', InfoFile),
 1847    read_file_to_terms(InfoFile, Info, [encoding(utf8)]),
 1848    maplist(valid_term(pack_info_term), Info).
 download_file_sanity_check(+Archive, +Pack, +Info) is semidet
Perform basic sanity checks on DownloadFile
 1854download_file_sanity_check(Archive, Pack, Info) :-
 1855    info_field(name(PackName), Info),
 1856    info_field(version(PackVersion), Info),
 1857    pack_version_file(PackFile, FileVersion, Archive),
 1858    must_match([Pack, PackName, PackFile], name),
 1859    must_match([PackVersion, FileVersion], version).
 1860
 1861info_field(Field, Info) :-
 1862    memberchk(Field, Info),
 1863    ground(Field),
 1864    !.
 1865info_field(Field, _Info) :-
 1866    functor(Field, FieldName, _),
 1867    print_message(error, pack(missing(FieldName))),
 1868    fail.
 1869
 1870must_match(Values, _Field) :-
 1871    sort(Values, [_]),
 1872    !.
 1873must_match(Values, Field) :-
 1874    print_message(error, pack(conflict(Field, Values))),
 1875    fail.
 1876
 1877
 1878                 /*******************************
 1879                 *         INSTALLATION         *
 1880                 *******************************/
 prepare_pack_dir(+Dir, +Options)
Prepare for installing the package into Dir. This
 1894prepare_pack_dir(Dir, Options) :-
 1895    exists_directory(Dir),
 1896    !,
 1897    (   empty_directory(Dir)
 1898    ->  true
 1899    ;   remove_existing_pack(Dir, Options)
 1900    ->  make_directory(Dir)
 1901    ).
 1902prepare_pack_dir(Dir, _) :-
 1903    (   read_link(Dir, _, _)
 1904    ;   access_file(Dir, exist)
 1905    ),
 1906    !,
 1907    delete_file(Dir),
 1908    make_directory(Dir).
 1909prepare_pack_dir(Dir, _) :-
 1910    make_directory(Dir).
 empty_directory(+Directory) is semidet
True if Directory is empty (holds no files or sub-directories).
 1916empty_directory(Dir) :-
 1917    \+ ( directory_files(Dir, Entries),
 1918         member(Entry, Entries),
 1919         \+ special(Entry)
 1920       ).
 1921
 1922special(.).
 1923special(..).
 remove_existing_pack(+PackDir, +Options) is semidet
Remove a possible existing pack directory if the option upgrade(true) is present. This is used to remove an old installation before unpacking a new archive, copy or link a directory with the new contents.
 1932remove_existing_pack(PackDir, Options) :-
 1933    exists_directory(PackDir),
 1934    !,
 1935    (   (   option(upgrade(true), Options)
 1936        ;   confirm(remove_existing_pack(PackDir), yes, Options)
 1937        )
 1938    ->  delete_directory_and_contents(PackDir)
 1939    ;   print_message(error, pack(directory_exists(PackDir))),
 1940        fail
 1941    ).
 1942remove_existing_pack(_, _).
 pack_download_from_url(+URL, +PackDir, +Pack, +Options)
Download a package from a remote source. For git repositories, we simply clone. Archives are downloaded. Options:
git(true)
Assume URL refers to a git repository.
pack_dir(-Dir)
Dir is unified with the location where the pack is installed.
To be done
- We currently use the built-in HTTP client. For complete coverage, we should consider using an external (e.g., curl) if available.
 1958pack_download_from_url(URL, PackTopDir, Pack, Options) :-
 1959    option(git(true), Options),
 1960    !,
 1961    directory_file_path(PackTopDir, Pack, PackDir),
 1962    prepare_pack_dir(PackDir, Options),
 1963    (   option(branch(Branch), Options)
 1964    ->  git_ref_argument(Branch),
 1965        Extra = ['--branch', Branch]
 1966    ;   Extra = []
 1967    ),
 1968    append([clone|Extra], ['--', URL, PackDir], Argv),
 1969    run_process(path(git), Argv, []),
 1970    git_checkout_version(PackDir, [update(false)|Options]),
 1971    option(pack_dir(PackDir), Options, _).
 1972pack_download_from_url(URL0, PackTopDir, Pack, Options) :-
 1973    download_url(URL0),
 1974    !,
 1975    hsts(URL0, URL, Options),
 1976    directory_file_path(PackTopDir, Pack, PackDir),
 1977    prepare_pack_dir(PackDir, Options),
 1978    pack_download_dir(PackTopDir, DownLoadDir),
 1979    download_file(URL, Pack, DownloadBase, Options),
 1980    directory_file_path(DownLoadDir, DownloadBase, DownloadFile),
 1981    (   option(insecure(true), Options, false)
 1982    ->  TLSOptions = [cert_verify_hook(ssl_verify)]
 1983    ;   TLSOptions = []
 1984    ),
 1985    print_message(informational, pack(download(begin, Pack, URL, DownloadFile))),
 1986    setup_call_cleanup(
 1987        http_open(URL, In, TLSOptions),
 1988        setup_call_cleanup(
 1989            open(DownloadFile, write, Out, [type(binary)]),
 1990            copy_stream_data(In, Out),
 1991            close(Out)),
 1992        close(In)),
 1993    print_message(informational, pack(download(end, Pack, URL, DownloadFile))),
 1994    verify_download_hash(DownloadFile, Pack, URL, Options),
 1995    pack_archive_info(DownloadFile, Pack, Info, _),
 1996    (   option(git_url(GitURL), Options)
 1997    ->  Origin = GitURL                 % implicit download from git.
 1998    ;   download_file_sanity_check(DownloadFile, Pack, Info),
 1999        Origin = URL
 2000    ),
 2001    pack_unpack_from_local(DownloadFile, PackTopDir, Pack, PackDir, Options),
 2002    pack_assert(PackDir, archive(DownloadFile, Origin)),
 2003    option(pack_dir(PackDir), Options, _).
 2004pack_download_from_url(URL, PackTopDir, Pack, Options) :-
 2005    local_uri_file_name(URL, File),
 2006    !,
 2007    pack_unpack_from_local(File, PackTopDir, Pack, PackDir, Options),
 2008    pack_assert(PackDir, archive(File, URL)),
 2009    option(pack_dir(PackDir), Options, _).
 2010pack_download_from_url(URL, _PackTopDir, _Pack, _Options) :-
 2011    domain_error(url, URL).
 verify_download_hash(+File, +Pack, +URL, +Options) is semidet
If the pack server provided the SHA1 hash of the archive as hash(Hash), verify that the downloaded File has this hash. On mismatch, ask the user if confirm_hash(true) is given and fail with an error message otherwise. Archives generated by GitHub are not verified as GitHub may regenerate them.
 2021verify_download_hash(File, Pack, URL, Options) :-
 2022    option(hash(Expected), Options),
 2023    \+ github_generated_archive(URL, Options),
 2024    !,
 2025    file_sha1(File, Hash),
 2026    (   Hash == Expected
 2027    ->  true
 2028    ;   Mismatch = hash_mismatch(Pack, URL, Expected, Hash),
 2029        (   option(confirm_hash(true), Options)
 2030        ->  print_message(warning, pack(Mismatch)),
 2031            confirm(accept_hash_mismatch, no, [])
 2032        ;   print_message(error, pack(Mismatch)),
 2033            fail
 2034        )
 2035    ).
 2036verify_download_hash(_, _, _, _).
 2037
 2038github_generated_archive(_URL, Options) :-
 2039    option(git_url(_), Options),
 2040    !.
 2041github_generated_archive(URL, _Options) :-
 2042    uri_components(URL, Components),
 2043    uri_data(authority, Components, Host),
 2044    memberchk(Host, ['github.com', 'codeload.github.com']).
 2045
 2046is_sha1(Hash) :-
 2047    atom(Hash),
 2048    atom_length(Hash, 40),
 2049    atom_codes(Hash, Codes),
 2050    forall(member(C, Codes), code_type(C, xdigit(_))).
 git_checkout_version(+PackDir, +Options) is det
Given a checked out version of a repository, put the repo at the desired version. Options:
commit(+Commit)
Target commit or 'HEAD'. If 'HEAD', get the HEAD of the explicit (option branch(Branch)), current or default branch. If the commit is a hash and it is the tip of a branch, checkout this branch. Else simply checkout the hash.
branch(+Branch)
Used with commit('HEAD').
version(+Version)
Checkout a tag. If there is a tag matching Version use that, otherwise try to find a tag that ends with Version and demand the prefix to be letters, optionally followed by a dash or underscore. Examples: 2.1, V2.1, v_2.1.
update(true)
If none of the above is given update the repo. If it is on a branch, pull. Else, put it on the default branch and pull.
 2074git_checkout_version(PackDir, Options) :-
 2075    option(commit('HEAD'), Options),
 2076    option(branch(Branch), Options),
 2077    !,
 2078    git_ensure_on_branch(PackDir, Branch),
 2079    run_process(path(git), ['-C', PackDir, pull], []).
 2080git_checkout_version(PackDir, Options) :-
 2081    option(commit('HEAD'), Options),
 2082    git_current_branch(_, [directory(PackDir)]),
 2083    !,
 2084    run_process(path(git), ['-C', PackDir, pull], []).
 2085git_checkout_version(PackDir, Options) :-
 2086    option(commit('HEAD'), Options),
 2087    !,
 2088    git_default_branch(Branch, [directory(PackDir)]),
 2089    git_ensure_on_branch(PackDir, Branch),
 2090    run_process(path(git), ['-C', PackDir, pull], []).
 2091git_checkout_version(PackDir, Options) :-
 2092    option(commit(Hash), Options),
 2093    run_process(path(git), ['-C', PackDir, fetch], []),
 2094    git_branches(Branches, [contains(Hash), directory(PackDir)]),
 2095    git_process_output(['-C', PackDir, 'rev-parse' | Branches],
 2096                       read_lines_to_atoms(Commits),
 2097                       []),
 2098    nth1(I, Commits, Hash),
 2099    nth1(I, Branches, Branch),
 2100    !,
 2101    git_ensure_on_branch(PackDir, Branch).
 2102git_checkout_version(PackDir, Options) :-
 2103    option(commit(Hash), Options),
 2104    !,
 2105    git_ref_argument(Hash),
 2106    run_process(path(git), ['-C', PackDir, checkout, '--quiet', Hash], []).
 2107git_checkout_version(PackDir, Options) :-
 2108    option(version(Version), Options),
 2109    !,
 2110    git_tags(Tags, [directory(PackDir)]),
 2111    (   memberchk(Version, Tags)
 2112    ->  Tag = Version
 2113    ;   member(Tag, Tags),
 2114        sub_atom(Tag, B, _, 0, Version),
 2115        sub_atom(Tag, 0, B, _, Prefix),
 2116        version_prefix(Prefix)
 2117    ->  true
 2118    ;   existence_error(version_tag, Version)
 2119    ),
 2120    git_ref_argument(Tag),
 2121    run_process(path(git), ['-C', PackDir, checkout, Tag], []).
 2122git_checkout_version(_PackDir, Options) :-
 2123    option(fresh(true), Options),
 2124    !.
 2125git_checkout_version(PackDir, _Options) :-
 2126    git_current_branch(_, [directory(PackDir)]),
 2127    !,
 2128    run_process(path(git), ['-C', PackDir, pull], []).
 2129git_checkout_version(PackDir, _Options) :-
 2130    git_default_branch(Branch, [directory(PackDir)]),
 2131    git_ensure_on_branch(PackDir, Branch),
 2132    run_process(path(git), ['-C', PackDir, pull], []).
 git_ensure_on_branch(+PackDir, +Branch) is det
Ensure PackDir is on Branch.
 2138git_ensure_on_branch(PackDir, Branch) :-
 2139    git_current_branch(Branch, [directory(PackDir)]),
 2140    !.
 2141git_ensure_on_branch(PackDir, Branch) :-
 2142    git_ref_argument(Branch),
 2143    run_process(path(git), ['-C', PackDir, checkout, Branch], []).
 2144
 2145%   git_ref_argument(+Ref) is det.
 2146%
 2147%   Ref is passed to git as a commit, tag or branch.  These may come from
 2148%   the pack server or repository.  Raise an error if git would process
 2149%   Ref as an option.
 2150
 2151git_ref_argument(Ref) :-
 2152    (   atomic(Ref),
 2153        sub_atom(Ref, 0, _, _, -)
 2154    ->  domain_error(git_ref, Ref)
 2155    ;   true
 2156    ).
 2157
 2158read_lines_to_atoms(Atoms, In) :-
 2159    read_line_to_string(In, Line),
 2160    (   Line == end_of_file
 2161    ->  Atoms = []
 2162    ;   atom_string(Atom, Line),
 2163        Atoms = [Atom|T],
 2164        read_lines_to_atoms(T, In)
 2165    ).
 2166
 2167version_prefix(Prefix) :-
 2168    atom_codes(Prefix, Codes),
 2169    phrase(version_prefix, Codes).
 2170
 2171version_prefix -->
 2172    [C],
 2173    { code_type(C, alpha) },
 2174    !,
 2175    version_prefix.
 2176version_prefix -->
 2177    "-".
 2178version_prefix -->
 2179    "_".
 2180version_prefix -->
 2181    "".
 download_file(+URL, +Pack, -File, +Options) is det
Determine the file into which to download URL. The second clause deals with GitHub downloads from a release tag.
 2188download_file(URL, Pack, File, Options) :-
 2189    option(version(Version), Options),
 2190    !,
 2191    file_name_extension(_, Ext, URL),
 2192    format(atom(File), '~w-~w.~w', [Pack, Version, Ext]).
 2193download_file(URL, Pack, File, _) :-
 2194    file_base_name(URL,Basename),
 2195    no_int_file_name_extension(Tag,Ext,Basename),
 2196    tag_version(Tag,Version),
 2197    !,
 2198    format(atom(File0), '~w-~w', [Pack, Version]),
 2199    file_name_extension(File0, Ext, File).
 2200download_file(URL, _, File, _) :-
 2201    file_base_name(URL, File).
 pack_url_file(+URL, -File) is det
True if File is a unique id for the referenced pack and version. Normally, that is simply the base name, but GitHub archives destroy this picture. Needed by the pack manager in the web server.
 2209:- public pack_url_file/2. 2210pack_url_file(URL, FileID) :-
 2211    github_release_url(URL, Pack, Version),
 2212    !,
 2213    download_file(URL, Pack, FileID, [version(Version)]).
 2214pack_url_file(URL, FileID) :-
 2215    file_base_name(URL, FileID).
 2216
 2217%   ssl_verify(+SSL, +ProblemCert, +AllCerts, +FirstCert, +Error)
 2218%
 2219%   Used if insecure(true)  is  given   to  pack_install/2.  Accepts any
 2220%   certificate.
 2221
 2222:- public ssl_verify/5. 2223ssl_verify(_SSL,
 2224           _ProblemCertificate, _AllCertificates, _FirstCertificate,
 2225           _Error).
 2226
 2227pack_download_dir(PackTopDir, DownLoadDir) :-
 2228    directory_file_path(PackTopDir, 'Downloads', DownLoadDir),
 2229    (   exists_directory(DownLoadDir)
 2230    ->  true
 2231    ;   make_directory(DownLoadDir)
 2232    ),
 2233    (   access_file(DownLoadDir, write)
 2234    ->  true
 2235    ;   permission_error(write, directory, DownLoadDir)
 2236    ).
 download_url(@URL) is semidet
True if URL looks like a URL we can download from. Noet that urls like ftp:// are also download URLs, but we cannot download from them.
 2244download_url(URL) :-
 2245    url_scheme(URL, Scheme),
 2246    download_scheme(Scheme).
 2247
 2248url_scheme(URL, Scheme) :-
 2249    atom(URL),
 2250    uri_components(URL, Components),
 2251    uri_data(scheme, Components, Scheme0),
 2252    atom(Scheme0),
 2253    Scheme = Scheme0.
 2254
 2255download_scheme(http).
 2256download_scheme(https).
 hsts(+URL0, -URL, +Options) is det
HSTS (HTTP Strict Transport Security) is standard by which means a site asks to always use HTTPS. For SWI-Prolog packages we now force using HTTPS for all downloads. This may be overrules using the option insecure(true), which may also be used to disable TLS certificate checking. Note that the integrity of archives is still verified against the SHA1 hash provided by the pack server (see verify_download_hash/4), except for archives generated by GitHub.
 2268hsts(URL0, URL, Options) :-
 2269    option(insecure(true), Options, false),
 2270    !,
 2271    URL = URL0.
 2272hsts(URL0, URL, _Options) :-
 2273    url_scheme(URL0, http),
 2274    !,
 2275    uri_edit(scheme(https), URL0, URL).
 2276hsts(URL, URL, _Options).
 pack_post_install(+Info, +Options) is det
Process post installation work. Steps:
 2287pack_post_install(Info, Options) :-
 2288    Pack = Info.pack,
 2289    PackDir = Info.installed,
 2290    post_install_foreign(Pack, PackDir, Options),
 2291    post_install_autoload(Info),
 2292    pack_attach(PackDir, [duplicate(warning)]).
 pack_rebuild is det
 pack_rebuild(+Pack) is det
Rebuild possible foreign components of Pack. The predicate pack_rebuild/0 rebuilds all registered packs.
 2300pack_rebuild :-
 2301    forall(current_pack(Pack),
 2302           ( print_message(informational, pack(rebuild(Pack))),
 2303             pack_rebuild(Pack)
 2304           )).
 2305
 2306pack_rebuild(Pack) :-
 2307    current_pack(Pack, PackDir),
 2308    !,
 2309    post_install_foreign(Pack, PackDir, [rebuild(true)]),
 2310	pack_attach(PackDir, [duplicate(replace)]).
 2311pack_rebuild(Pack) :-
 2312    unattached_pack(Pack, PackDir),
 2313    !,
 2314    post_install_foreign(Pack, PackDir, [rebuild(true)]),
 2315	pack_attach(PackDir, [duplicate(replace)]).
 2316pack_rebuild(Pack) :-
 2317    existence_error(pack, Pack).
 2318
 2319unattached_pack(Pack, BaseDir) :-
 2320    directory_file_path(Pack, 'pack.pl', PackFile),
 2321    absolute_file_name(pack(PackFile), PackPath,
 2322                       [ access(read),
 2323                         file_errors(fail)
 2324                       ]),
 2325    file_directory_name(PackPath, BaseDir).
 post_install_foreign(+Pack, +PackDir, +Options) is det
Install foreign parts of the package. Options:
rebuild(When)
Determine when to rebuild. Possible values:
if_absent
Only rebuild if we have no existing foreign library. This is the default.
true
Always rebuild.
 2341post_install_foreign(Pack, PackDir, Options) :-
 2342    is_foreign_pack(PackDir, _),
 2343    !,
 2344    (   pack_info_term(PackDir, pack_version(Version))
 2345    ->  true
 2346    ;   Version = 1
 2347    ),
 2348    option(rebuild(Rebuild), Options, if_absent),
 2349    current_prolog_flag(arch, Arch),
 2350    prolog_version_dotted(PrologVersion),
 2351    (   Rebuild == if_absent,
 2352        foreign_present(PackDir, Arch)
 2353    ->  print_message(informational, pack(kept_foreign(Pack, Arch))),
 2354        (   pack_status_dir(PackDir, built(Arch, _, _))
 2355        ->  true
 2356        ;   pack_assert(PackDir, built(Arch, PrologVersion, downloaded))
 2357        )
 2358    ;   BuildSteps0 = [[dependencies], [configure], build, install, [test]],
 2359        (   Rebuild == true
 2360        ->  BuildSteps1 = [distclean|BuildSteps0]
 2361        ;   BuildSteps1 = BuildSteps0
 2362        ),
 2363        (   option(test(false), Options)
 2364        ->  delete(BuildSteps1, [test], BuildSteps2)
 2365        ;   BuildSteps2 = BuildSteps1
 2366        ),
 2367        (   option(clean(true), Options)
 2368        ->  append(BuildSteps2, [[clean]], BuildSteps)
 2369        ;   BuildSteps = BuildSteps2
 2370        ),
 2371        build_steps(BuildSteps, PackDir, [pack_version(Version)|Options]),
 2372        pack_assert(PackDir, built(Arch, PrologVersion, built))
 2373    ).
 2374post_install_foreign(_, _, _).
 foreign_present(+PackDir, +Arch) is semidet
True if we find one or more modules in the pack lib directory for the current architecture.
To be done
- Does not check that these can be loaded, nor whether all required modules are present.
 2385foreign_present(PackDir, Arch) :-
 2386    atomic_list_concat([PackDir, '/lib'], ForeignBaseDir),
 2387    exists_directory(ForeignBaseDir),
 2388    !,
 2389    atomic_list_concat([PackDir, '/lib/', Arch], ForeignDir),
 2390    exists_directory(ForeignDir),
 2391    current_prolog_flag(shared_object_extension, Ext),
 2392    atomic_list_concat([ForeignDir, '/*.', Ext], Pattern),
 2393    expand_file_name(Pattern, Files),
 2394    Files \== [].
 is_foreign_pack(+PackDir, -Type) is nondet
True when PackDir contains files that indicate the need for a specific class of build tools indicated by Type.
 2401is_foreign_pack(PackDir, Type) :-
 2402    foreign_file(File, Type),
 2403    directory_file_path(PackDir, File, Path),
 2404    exists_file(Path).
 2405
 2406foreign_file('CMakeLists.txt', cmake).
 2407foreign_file('configure',      configure).
 2408foreign_file('configure.in',   autoconf).
 2409foreign_file('configure.ac',   autoconf).
 2410foreign_file('Makefile.am',    automake).
 2411foreign_file('Makefile',       make).
 2412foreign_file('makefile',       make).
 2413foreign_file('conanfile.txt',  conan).
 2414foreign_file('conanfile.py',   conan).
 2415
 2416
 2417                 /*******************************
 2418                 *           AUTOLOAD           *
 2419                 *******************************/
 post_install_autoload(+InfoOrList) is det
Create an autoload index if the package demands such.
 2425post_install_autoload(List), is_list(List) =>
 2426    maplist(post_install_autoload, List).
 2427post_install_autoload(Info),
 2428    _{installed:PackDir, autoload:true} :< Info =>
 2429    directory_file_path(PackDir, prolog, PrologLibDir),
 2430    make_library_index(PrologLibDir).
 2431post_install_autoload(Info) =>
 2432    directory_file_path(Info.installed, 'prolog/INDEX.pl', IndexFile),
 2433    (   exists_file(IndexFile)
 2434    ->  E = error(_,_),
 2435        print_message(warning, pack(delete_autoload_index(Info.pack, IndexFile))),
 2436        catch(delete_file(IndexFile), E,
 2437              print_message(warning, E))
 2438    ;   true
 2439    ).
 decide_autoload_pack(+Options, +Info0, -Info) is det
Add autoload:true to Info if the pack needs to be configured for autoloading.
 2446decide_autoload_pack(Options, Info0, Info) :-
 2447    is_autoload_pack(Info0.pack, Info0.installed, Options),
 2448    !,
 2449    Info = Info0.put(autoload, true).
 2450decide_autoload_pack(_, Info, Info).
 2451
 2452is_autoload_pack(_Pack, _PackDir, Options) :-
 2453    option(autoload(true), Options),
 2454    !.
 2455is_autoload_pack(Pack, PackDir, Options) :-
 2456    pack_info_term(PackDir, autoload(true)),
 2457    confirm(autoload(Pack), no, Options).
 2458
 2459
 2460                 /*******************************
 2461                 *            UPGRADE           *
 2462                 *******************************/
 pack_upgrade(+Pack) is semidet
Upgrade Pack. Shorthand for pack_install(Pack, [upgrade(true)]).
 2468pack_upgrade(Pack) :-
 2469    pack_install(Pack, [upgrade(true)]).
 2470
 2471
 2472                 /*******************************
 2473                 *            REMOVE            *
 2474                 *******************************/
 pack_remove(+Name) is det
 pack_remove(+Name, +Options) is det
Remove the indicated package. If packages depend (indirectly) on this pack, ask to remove these as well. Options:
interactive(false)
Do not prompt the user.
dependencies(Boolean)
If true delete dependencies without asking.
 2487pack_remove(Pack) :-
 2488    pack_remove(Pack, []).
 2489
 2490pack_remove(Pack, Options) :-
 2491    option(dependencies(false), Options),
 2492    !,
 2493    pack_remove_forced(Pack).
 2494pack_remove(Pack, Options) :-
 2495    (   dependents(Pack, Deps)
 2496    ->  (   option(dependencies(true), Options)
 2497        ->  true
 2498        ;   confirm_remove(Pack, Deps, Delete, Options)
 2499        ),
 2500        forall(member(P, Delete), pack_remove_forced(P))
 2501    ;   pack_remove_forced(Pack)
 2502    ).
 2503
 2504pack_remove_forced(Pack) :-
 2505    catch('$pack_detach'(Pack, BaseDir),
 2506          error(existence_error(pack, Pack), _),
 2507          fail),
 2508    !,
 2509    (   read_link(BaseDir, _, Target)
 2510    ->  What = link(Target)
 2511    ;   What = directory
 2512    ),
 2513    print_message(informational, pack(remove(What, BaseDir))),
 2514    delete_directory_and_contents(BaseDir).
 2515pack_remove_forced(Pack) :-
 2516    unattached_pack(Pack, BaseDir),
 2517    !,
 2518    delete_directory_and_contents(BaseDir).
 2519pack_remove_forced(Pack) :-
 2520    print_message(informational, error(existence_error(pack, Pack),_)).
 2521
 2522confirm_remove(Pack, Deps, Delete, Options) :-
 2523    print_message(warning, pack(depends(Pack, Deps))),
 2524    menu(pack(resolve_remove),
 2525         [ [Pack]      = remove_only(Pack),
 2526           [Pack|Deps] = remove_deps(Pack, Deps),
 2527           []          = cancel
 2528         ], [], Delete, Options),
 2529    Delete \== [].
 2530
 2531
 2532		 /*******************************
 2533		 *           PUBLISH		*
 2534		 *******************************/
 pack_publish(+Spec, +Options) is det
Publish a package. There are two ways typical ways to call this. We recommend developing a pack in a GIT repository. In this scenario the pack can be published using
?- pack_publish('.', []).

Alternatively, an archive file has been uploaded to a public location. In this scenario we can publish the pack using

?- pack_publish(URL, [])

In both scenarios, pack_publish/2 by default creates an isolated environment and installs the package in this directory from the public URL. On success it triggers the pack server to register the URL as a new pack or a new release of a pack.

Packs may also be published using the app pack, e.g.

swipl pack publish .

Options:

git(Boolean)
If true, and Spec is a git managed directory, install using the remote repo.
sign(Boolean)
Sign the repository with the current version. This runs git tag -s <tag>.
force(Boolean)
Force the git tag. This runs git tag -f <tag>.
branch(+Branch)
Branch used for releases. Defined by git_default_branch/2 if not specified.
register(+Boolean)
If false (default true), perform the installation, but do not upload to the server. This can be used for testing.
isolated(+Boolean)
If true (default), install and build all packages in an isolated package directory. If false, use other packages installed for the environment. The latter may be used to speedup debugging.
pack_directory(+Dir)
Install the temporary packages in Dir. If omitted pack_publish/2 creates a temporary directory and deletes this directory after completion. An explict target Dir is created if it does not exist and is not deleted on completion.
clean(+Boolean)
If true (default), clean the destination directory first
 2587pack_publish(Dir, Options) :-
 2588    \+ download_url(Dir),
 2589    is_git_directory(Dir), !,
 2590    pack_git_info(Dir, _Hash, Metadata),
 2591    prepare_repository(Dir, Metadata, Options),
 2592    (   memberchk(download(URL), Metadata),
 2593        git_url(URL, _, Options)
 2594    ->  true
 2595    ;   option(remote(Remote), Options, origin),
 2596        git_remote_url(Remote, RemoteURL, [directory(Dir)]),
 2597        git_to_https_url(RemoteURL, URL)
 2598    ),
 2599    memberchk(version(Version), Metadata),
 2600    memberchk(name(Pack), Metadata),
 2601    pack_publish_(URL,
 2602                  [ version(Version),
 2603                    pack(Pack)
 2604                  | Options
 2605                  ]).
 2606pack_publish(Spec, Options) :-
 2607    pack_publish_(Spec, Options).
 2608
 2609pack_publish_(Spec, Options) :-
 2610    pack_default_options(Spec, Pack, Options, DefOptions),
 2611    option(url(URL), DefOptions),
 2612    valid_publish_url(URL, Options),
 2613    prepare_build_location(Pack, Dir, Clean, Options),
 2614    (   option(register(false), Options)
 2615    ->  InstallOptions = DefOptions
 2616    ;   InstallOptions = [publish(Pack)|DefOptions]
 2617    ),
 2618    call_cleanup(pack_install(Pack,
 2619                              [ pack(Pack)
 2620                              | InstallOptions
 2621                              ]),
 2622                 cleanup_publish(Clean, Dir)).
 2623
 2624cleanup_publish(true, Dir) :-
 2625    !,
 2626    delete_directory_and_contents(Dir).
 2627cleanup_publish(_, _).
 2628
 2629valid_publish_url(URL, Options) :-
 2630    option(register(Register), Options, true),
 2631    (   Register == false
 2632    ->  true
 2633    ;   download_url(URL)
 2634    ->  true
 2635    ;   permission_error(publish, pack, URL)
 2636    ).
 2637
 2638prepare_build_location(Pack, Dir, Clean, Options) :-
 2639    (   option(pack_directory(Dir), Options)
 2640    ->  ensure_directory(Dir),
 2641        (   option(clean(true), Options, true)
 2642        ->  delete_directory_contents(Dir)
 2643        ;   true
 2644        )
 2645    ;   tmp_directory(pack, Dir),
 2646        Clean = true
 2647    ),
 2648    (   option(isolated(false), Options)
 2649    ->  detach_pack(Pack, _),
 2650        attach_packs(Dir, [search(first)])
 2651    ;   attach_packs(Dir, [replace(true)])
 2652    ).
 prepare_repository(+Dir, +Metadata, +Options) is semidet
Prepare the git repository. If register(false) is provided, this is a test run and therefore we do not need this. Otherwise we demand the working directory to be clean, we tag the current commit and push the current branch.
 2663prepare_repository(_Dir, _Metadata, Options) :-
 2664    option(register(false), Options),
 2665    !.
 2666prepare_repository(Dir, Metadata, Options) :-
 2667    git_dir_must_be_clean(Dir),
 2668    git_must_be_on_default_branch(Dir, Options),
 2669    tag_git_dir(Dir, Metadata, Action, Options),
 2670    confirm(git_push, yes, Options),
 2671    run_process(path(git), ['-C', file(Dir), push ], []),
 2672    (   Action = push_tag(Tag)
 2673    ->  run_process(path(git), ['-C', file(Dir), push, origin, Tag ], [])
 2674    ;   true
 2675    ).
 2676
 2677git_dir_must_be_clean(Dir) :-
 2678    git_describe(Description, [directory(Dir)]),
 2679    (   sub_atom(Description, _, _, 0, '-DIRTY')
 2680    ->  print_message(error, pack(git_not_clean(Dir))),
 2681        fail
 2682    ;   true
 2683    ).
 2684
 2685git_must_be_on_default_branch(Dir, Options) :-
 2686    (   option(branch(Default), Options)
 2687    ->  true
 2688    ;   git_default_branch(Default, [directory(Dir)])
 2689    ),
 2690    git_current_branch(Current, [directory(Dir)]),
 2691    (   Default == Current
 2692    ->  true
 2693    ;   print_message(error,
 2694                      pack(git_branch_not_default(Dir, Default, Current))),
 2695        fail
 2696    ).
 tag_git_dir(+Dir, +Metadata, -Action, +Options) is semidet
Add a version tag to the git repository.
Arguments:
Action- is one of push_tag(Tag) or none
 2705tag_git_dir(Dir, Metadata, Action, Options) :-
 2706    memberchk(version(Version), Metadata),
 2707    atom_concat('V', Version, Tag),
 2708    git_tags(Tags, [directory(Dir)]),
 2709    (   memberchk(Tag, Tags)
 2710    ->  git_tag_is_consistent(Dir, Tag, Action, Options)
 2711    ;   format(string(Message), 'Release ~w', [Version]),
 2712        findall(Opt, git_tag_option(Opt, Options), Argv,
 2713                [ '-m', Message, Tag ]),
 2714        confirm(git_tag(Tag), yes, Options),
 2715        run_process(path(git), ['-C', file(Dir), tag | Argv ], []),
 2716        Action = push_tag(Tag)
 2717    ).
 2718
 2719git_tag_option('-s', Options) :- option(sign(true), Options, true).
 2720git_tag_option('-f', Options) :- option(force(true), Options, true).
 2721
 2722git_tag_is_consistent(Dir, Tag, Action, Options) :-
 2723    format(atom(TagRef), 'refs/tags/~w', [Tag]),
 2724    format(atom(CommitRef), 'refs/tags/~w^{}', [Tag]),
 2725    option(remote(Remote), Options, origin),
 2726    git_ls_remote(Dir, LocalTags, [tags(true)]),
 2727    memberchk(CommitHash-CommitRef, LocalTags),
 2728    (   git_hash(CommitHash, [directory(Dir)])
 2729    ->  true
 2730    ;   print_message(error, pack(git_release_tag_not_at_head(Tag))),
 2731        fail
 2732    ),
 2733    memberchk(TagHash-TagRef, LocalTags),
 2734    git_ls_remote(Remote, RemoteTags, [tags(true)]),
 2735    (   memberchk(RemoteCommitHash-CommitRef, RemoteTags),
 2736        memberchk(RemoteTagHash-TagRef, RemoteTags)
 2737    ->  (   RemoteCommitHash == CommitHash,
 2738            RemoteTagHash == TagHash
 2739        ->  Action = none
 2740        ;   print_message(error, pack(git_tag_out_of_sync(Tag))),
 2741            fail
 2742        )
 2743    ;   Action = push_tag(Tag)
 2744    ).
 git_to_https_url(+GitURL, -HTTP_URL) is semidet
Get the HTTP(s) URL for a git repository, given a git url. Whether or not this is available and how to translate the one into the other depends in the server software.
 2752git_to_https_url(URL, URL) :-
 2753    download_url(URL),
 2754    !.
 2755git_to_https_url(GitURL, URL) :-
 2756    atom_concat('git@github.com:', Repo, GitURL),
 2757    !,
 2758    atom_concat('https://github.com/', Repo, URL).
 2759git_to_https_url(GitURL, _) :-
 2760    print_message(error, pack(git_no_https(GitURL))),
 2761    fail.
 2762
 2763
 2764                 /*******************************
 2765                 *           PROPERTIES         *
 2766                 *******************************/
 pack_property(?Pack, ?Property) is nondet
True when Property is a property of an installed Pack. This interface is intended for programs that wish to interact with the package manager. Defined properties are:
directory(Directory)
Directory into which the package is installed
version(Version)
Installed version
title(Title)
Full title of the package
author(Author)
Registered author
download(URL)
Official download URL
readme(File)
Package README file (if present)
todo(File)
Package TODO file (if present)
 2789pack_property(Pack, Property) :-
 2790    findall(Pack-Property, pack_property_(Pack, Property), List),
 2791    member(Pack-Property, List).            % make det if applicable
 2792
 2793pack_property_(Pack, Property) :-
 2794    pack_info(Pack, _, Property).
 2795pack_property_(Pack, Property) :-
 2796    \+ \+ info_file(Property, _),
 2797    '$pack':pack(Pack, BaseDir),
 2798    access_file(BaseDir, read),
 2799    directory_files(BaseDir, Files),
 2800    member(File, Files),
 2801    info_file(Property, Pattern),
 2802    downcase_atom(File, Pattern),
 2803    directory_file_path(BaseDir, File, InfoFile),
 2804    arg(1, Property, InfoFile).
 2805
 2806info_file(readme(_), 'readme.txt').
 2807info_file(readme(_), 'readme').
 2808info_file(todo(_),   'todo.txt').
 2809info_file(todo(_),   'todo').
 2810
 2811
 2812                 /*******************************
 2813                 *         VERSION LOGIC        *
 2814                 *******************************/
 pack_version_file(-Pack, -Version:atom, +File) is semidet
True if File is the name of a file or URL of a file that contains Pack at Version. File must have an extension and the basename must be of the form <pack>-<n>{.<m>}*. E.g., mypack-1.5.
 2823pack_version_file(Pack, Version, GitHubRelease) :-
 2824    atomic(GitHubRelease),
 2825    github_release_url(GitHubRelease, Pack, Version),
 2826    !.
 2827pack_version_file(Pack, Version, Path) :-
 2828    atomic(Path),
 2829    file_base_name(Path, File),
 2830    no_int_file_name_extension(Base, _Ext, File),
 2831    atom_codes(Base, Codes),
 2832    (   phrase(pack_version(Pack, Version), Codes),
 2833        safe_pack_name(Pack)
 2834    ->  true
 2835    ).
 2836
 2837no_int_file_name_extension(Base, Ext, File) :-
 2838    file_name_extension(Base0, Ext0, File),
 2839    \+ atom_number(Ext0, _),
 2840    !,
 2841    Base = Base0,
 2842    Ext = Ext0.
 2843no_int_file_name_extension(File, '', File).
 safe_pack_name(+Name:atom) is semidet
Verifies that Name is a valid pack name. This avoids trickery with pack file names to make shell commands behave unexpectly.
 2850safe_pack_name(Name) :-
 2851    atom_length(Name, Len),
 2852    Len >= 3,                               % demand at least three length
 2853    atom_codes(Name, Codes),
 2854    maplist(safe_pack_char, Codes),
 2855    !.
 2856
 2857safe_pack_char(C) :- between(0'a, 0'z, C), !.
 2858safe_pack_char(C) :- between(0'A, 0'Z, C), !.
 2859safe_pack_char(C) :- between(0'0, 0'9, C), !.
 2860safe_pack_char(0'_).
 consistent_pack_name(+Pack, +Repo) is det
The claimed pack name must match the repository name. Future versions might allow for a prefix, e.g., `prolog_<pack>`, etc.
Arguments:
Repo- is the basename of the GIT repository (no directory, no extension).
 2870consistent_pack_name(Pack, Pack) :-
 2871    !.
 2872consistent_pack_name(Pack, Repo) :-
 2873    downcase_atom(Pack, Lwr),
 2874    downcase_atom(Repo, Lwr),
 2875    !.
 2876consistent_pack_name(Pack, Repo) :-
 2877    format(string(Msg), "Pack name must match repository name (~w)", [Repo]),
 2878    throw(error(permission_error(Pack, name, pack),
 2879                context(_, Msg))).
 pack_version(-Pack:atom, -Version:atom)// is semidet
True when the input statifies <pack>-<version>
 2885pack_version(Pack, Version) -->
 2886    string(Codes), "-",
 2887    version(Parts),
 2888    !,
 2889    { atom_codes(Pack, Codes),
 2890      atomic_list_concat(Parts, '.', Version)
 2891    }.
 2892
 2893version([H|T]) -->
 2894    version_part(H),
 2895    (   "."
 2896    ->  version(T)
 2897    ;   {T=[]}
 2898    ).
 2899
 2900version_part(*) --> "*", !.
 2901version_part(Int) --> integer(Int).
 2902
 2903
 2904		 /*******************************
 2905		 *           GIT LOGIC		*
 2906		 *******************************/
 have_git is semidet
True if we have the git program. This could be simple, but Apple decided to include a fake `/usr/bin/git` that triggers the Xcode installation. So, if we find git at `/usr/bin/git` we should check that Xcode is properly enabled. This is the case if xcode-select -p points at an Xcode installation. Note that if we find git at some other location, we assume it is installed by the user, Macports, Homebrew or something else.
 2918have_git :-
 2919    process_which(path(git), GIT),
 2920    is_sane_git(GIT).
 2921
 2922:- if(current_prolog_flag(apple, true)). 2923sane_xcode_path -->
 2924    "Xcode.app/Contents".
 2925sane_xcode_path -->
 2926    "CommandLineTools".
 2927
 2928is_sane_git('/usr/bin/git') :-
 2929    !,
 2930    process_which(path('xcode-select'), XSpath),
 2931    catch(run_process(XSpath,['-p'],[output(Output),error(_)]), error(_,_), fail),
 2932    once(phrase((string(_), sane_xcode_path), Output, _)).
 2933:- endif. 2934is_sane_git(_).
 git_url(+URL, -Pack, +Options) is semidet
True if URL describes a git url for Pack
 2940git_url(URL, Pack, Options) :-
 2941    uri_components(URL, Components),
 2942    uri_data(scheme, Components, Scheme),
 2943    nonvar(Scheme),                         % must be full URL
 2944    uri_data(path, Components, Path),
 2945    (   Scheme == git
 2946    ->  true
 2947    ;   git_download_scheme(Scheme),
 2948        file_name_extension(_, git, Path)
 2949    ;   git_download_scheme(Scheme),
 2950        catch(git_ls_remote(URL, _, [refs(['HEAD']), error(_)]), _, fail)
 2951    ->  true
 2952    ),
 2953    file_base_name(Path, PackExt),
 2954    (   file_name_extension(PackFromRepo, git, PackExt)
 2955    ->  true
 2956    ;   PackFromRepo = PackExt
 2957    ),
 2958    option(pack(Pack), Options, PackFromRepo),
 2959    (   safe_pack_name(Pack)
 2960    ->  consistent_pack_name(Pack, PackFromRepo)
 2961    ;   domain_error(pack_name, Pack)
 2962    ).
 2963
 2964git_download_scheme(http).
 2965git_download_scheme(https).
 github_release_url(+URL, -Pack, -Version:atom) is semidet
True when URL is the URL of a GitHub release. Such releases are accessible as
https:/github.com/<owner>/<pack>/archive/[vV]?<version>.zip'
 2974github_release_url(URL, Pack, Version) :-
 2975    uri_components(URL, Components),
 2976    uri_data(authority, Components, 'github.com'),
 2977    uri_data(scheme, Components, Scheme),
 2978    download_scheme(Scheme),
 2979    uri_data(path, Components, Path),
 2980    github_archive_path(Archive,Pack,File),
 2981    atomic_list_concat(Archive, /, Path),
 2982    file_name_extension(Tag, Ext, File),
 2983    github_archive_extension(Ext),
 2984    tag_version(Tag, Version),
 2985    !.
 2986
 2987github_archive_path(['',_User,Pack,archive,File],Pack,File).
 2988github_archive_path(['',_User,Pack,archive,refs,tags,File],Pack,File).
 2989
 2990github_archive_extension(tgz).
 2991github_archive_extension(zip).
 tag_version(+GitTag, -Version) is semidet
True when a GIT tag describes version Version. GitTag must satisfy [vV]?int(\.int)*.
 2998tag_version(Tag, Version) :-
 2999    version_tag_prefix(Prefix),
 3000    atom_concat(Prefix, Version, Tag),
 3001    is_version(Version).
 3002
 3003version_tag_prefix(v).
 3004version_tag_prefix('V').
 3005version_tag_prefix('').
 git_archive_url(+URL, -Archive, +Options) is semidet
If we do not have git installed, some git services offer downloading the code as an archive using HTTP. This predicate makes this translation.
 3014git_archive_url(URL, Archive, Options) :-
 3015    uri_components(URL, Components),
 3016    uri_data(authority, Components, 'github.com'),
 3017    uri_data(path, Components, Path),
 3018    atomic_list_concat(['', User, RepoGit], /, Path),
 3019    $,
 3020    remove_git_ext(RepoGit, Repo),
 3021    git_archive_version(Version, Options),
 3022    atomic_list_concat(['', User, Repo, zip, Version], /, ArchivePath),
 3023    uri_edit([ path(ArchivePath),
 3024               host('codeload.github.com')
 3025             ],
 3026             URL, Archive).
 3027git_archive_url(URL, _, _) :-
 3028    print_message(error, pack(no_git(URL))),
 3029    fail.
 3030
 3031remove_git_ext(RepoGit, Repo) :-
 3032    file_name_extension(Repo, git, RepoGit),
 3033    !.
 3034remove_git_ext(Repo, Repo).
 3035
 3036git_archive_version(Version, Options) :-
 3037    option(commit(Version), Options),
 3038    !.
 3039git_archive_version(Version, Options) :-
 3040    option(branch(Version), Options),
 3041    !.
 3042git_archive_version(Version, Options) :-
 3043    option(version(Version), Options),
 3044    !.
 3045git_archive_version('HEAD', _).
 3046
 3047                 /*******************************
 3048                 *       QUERY CENTRAL DB       *
 3049                 *******************************/
 publish_download(+Infos, +Options) is semidet
 register_downloads(+Infos, +Options) is det
Register our downloads with the pack server. The publish_download/2 version is used to register a specific pack after successfully installing the pack. In this scenario, we
  1. call register_downloads/2 with publish(Pack) that must be a no-op.
  2. build and test the pack
  3. call publish_download/2, which calls register_downloads/2 after replacing publish(Pack) by do_publish(Pack).
 3064register_downloads(_, Options) :-
 3065    option(register(false), Options),
 3066    !.
 3067register_downloads(_, Options) :-
 3068    option(publish(_), Options),
 3069    !.
 3070register_downloads(Infos, Options) :-
 3071    convlist(download_data, Infos, Data),
 3072    (   Data == []
 3073    ->  true
 3074    ;   query_pack_server(downloaded(Data), Reply, Options),
 3075        (   option(do_publish(Pack), Options)
 3076        ->  (   member(Info, Infos),
 3077                Info.pack == Pack
 3078            ->  true
 3079            ),
 3080            (   Reply = true(Actions),
 3081                memberchk(Pack-Result, Actions)
 3082            ->  (   registered(Result)
 3083                ->  print_message(informational, pack(published(Info, Result)))
 3084                ;   print_message(error, pack(publish_failed(Info, Result))),
 3085                    fail
 3086                )
 3087            ;   print_message(error, pack(publish_failed(Info, false)))
 3088            )
 3089        ;   true
 3090        )
 3091    ).
 3092
 3093registered(git(_URL)).
 3094registered(file(_URL)).
 3095
 3096publish_download(Infos, Options) :-
 3097    select_option(publish(Pack), Options, Options1),
 3098    !,
 3099    register_downloads(Infos, [do_publish(Pack)|Options1]).
 3100publish_download(_Infos, _Options).
 download_data(+Info, -Data) is semidet
If we downloaded and installed Info, unify Data with the information that we share with the pack registry. That is a term
download(URL, Hash, Metadata).

Where URL is location of the GIT repository or URL of the download archive. Hash is either the GIT commit hash or the SHA1 of the archive file.

 3113download_data(Info, Data),
 3114    Info.get(git) == true =>                % Git clone
 3115    Data = download(URL, Hash, Metadata),
 3116    URL = Info.get(downloaded),
 3117    pack_git_info(Info.installed, Hash, Metadata).
 3118download_data(Info, Data),
 3119    _{git_url:URL,hash:Hash} :< Info, Hash \== (-) =>
 3120    Data = download(URL, Hash, Metadata),   % Git downloaded as zip
 3121    dir_metadata(Info.installed, Metadata).
 3122download_data(Info, Data) =>                % Archive download.
 3123    Data = download(URL, Hash, Metadata),
 3124    URL = Info.get(downloaded),
 3125    download_url(URL),
 3126    pack_status_dir(Info.installed, archive(Archive, URL)),
 3127    file_sha1(Archive, Hash),
 3128    pack_archive_info(Archive, _Pack, Metadata, _).
 query_pack_server(+Query, -Result, +Options)
Send a Prolog query to the package server and process its results.
 3135query_pack_server(Query, Result, Options) :-
 3136    (   option(server(ServerOpt), Options)
 3137    ->  server_url(ServerOpt, ServerBase)
 3138    ;   setting(server, ServerBase),
 3139        ServerBase \== ''
 3140    ),
 3141    atom_concat(ServerBase, query, Server),
 3142    format(codes(Data), '~q.~n', Query),
 3143    info_level(Informational, Options),
 3144    print_message(Informational, pack(contacting_server(Server))),
 3145    setup_call_cleanup(
 3146        http_open(Server, In,
 3147                  [ post(codes(application/'x-prolog', Data)),
 3148                    header(content_type, ContentType)
 3149                  ]),
 3150        read_reply(ContentType, In, Result),
 3151        close(In)),
 3152    message_severity(Result, Level, Informational),
 3153    print_message(Level, pack(server_reply(Result))).
 3154
 3155server_url(URL0, URL) :-
 3156    uri_components(URL0, Components),
 3157    uri_data(scheme, Components, Scheme),
 3158    var(Scheme),
 3159    !,
 3160    atom_concat('https://', URL0, URL1),
 3161    server_url(URL1, URL).
 3162server_url(URL0, URL) :-
 3163    uri_components(URL0, Components),
 3164    uri_data(path, Components, ''),
 3165    !,
 3166    uri_edit([path('/pack/')], URL0, URL).
 3167server_url(URL, URL).
 3168
 3169read_reply(ContentType, In, Result) :-
 3170    sub_atom(ContentType, 0, _, _, 'application/x-prolog'),
 3171    !,
 3172    set_stream(In, encoding(utf8)),
 3173    read(In, Result).
 3174read_reply(ContentType, In, _Result) :-
 3175    read_string(In, 500, String),
 3176    print_message(error, pack(no_prolog_response(ContentType, String))),
 3177    fail.
 3178
 3179info_level(Level, Options) :-
 3180    option(silent(true), Options),
 3181    !,
 3182    Level = silent.
 3183info_level(informational, _).
 3184
 3185message_severity(true(_), Informational, Informational).
 3186message_severity(false, warning, _).
 3187message_severity(exception(_), error, _).
 3188
 3189
 3190                 /*******************************
 3191                 *        WILDCARD URIs         *
 3192                 *******************************/
 available_download_versions(+URL, -Versions:list(atom), +Options) is det
Deal with wildcard URLs, returning a list of Version-URL pairs, sorted by version.
To be done
- Deal with protocols other than HTTP
 3201available_download_versions(URL, Versions, _Options) :-
 3202    wildcard_pattern(URL),
 3203    github_url(URL, User, Repo),            % demands https
 3204    !,
 3205    findall(Version-VersionURL,
 3206            github_version(User, Repo, Version, VersionURL),
 3207            Versions).
 3208available_download_versions(URL0, Versions, Options) :-
 3209    wildcard_pattern(URL0),
 3210    !,
 3211    hsts(URL0, URL, Options),
 3212    file_directory_name(URL, DirURL0),
 3213    ensure_slash(DirURL0, DirURL),
 3214    print_message(informational, pack(query_versions(DirURL))),
 3215    setup_call_cleanup(
 3216        http_open(DirURL, In, []),
 3217        load_html(stream(In), DOM,
 3218                  [ syntax_errors(quiet)
 3219                  ]),
 3220        close(In)),
 3221    findall(MatchingURL,
 3222            absolute_matching_href(DOM, URL, MatchingURL),
 3223            MatchingURLs),
 3224    (   MatchingURLs == []
 3225    ->  print_message(warning, pack(no_matching_urls(URL)))
 3226    ;   true
 3227    ),
 3228    versioned_urls(MatchingURLs, VersionedURLs),
 3229    sort_version_pairs(VersionedURLs, Versions),
 3230    print_message(informational, pack(found_versions(Versions))).
 3231available_download_versions(URL, [Version-URL], _Options) :-
 3232    (   pack_version_file(_Pack, Version0, URL)
 3233    ->  Version = Version0
 3234    ;   Version = '0.0.0'
 3235    ).
 sort_version_pairs(+Pairs, -Sorted) is det
Sort a list of Version-Data by decreasing version.
 3241sort_version_pairs(Pairs, Sorted) :-
 3242    map_list_to_pairs(version_pair_sort_key_, Pairs, Keyed),
 3243    sort(1, @>=, Keyed, SortedKeyed),
 3244    pairs_values(SortedKeyed, Sorted).
 3245
 3246version_pair_sort_key_(Version-_Data, Key) :-
 3247    version_sort_key(Version, Key).
 3248
 3249version_sort_key(Version, Key) :-
 3250    split_string(Version, ".", "", Parts),
 3251    maplist(number_string, Key, Parts),
 3252    !.
 3253version_sort_key(Version, _) :-
 3254    domain_error(version, Version).
 github_url(+URL, -User, -Repo) is semidet
True when URL refers to a github repository.
 3260github_url(URL, User, Repo) :-
 3261    uri_components(URL, uri_components(https,'github.com',Path,_,_)),
 3262    atomic_list_concat(['',User,Repo|_], /, Path).
 github_version(+User, +Repo, -Version, -VersionURI) is nondet
True when Version is a release version and VersionURI is the download location for the zip file.
 3270github_version(User, Repo, Version, VersionURI) :-
 3271    atomic_list_concat(['',repos,User,Repo,tags], /, Path1),
 3272    uri_components(ApiUri, uri_components(https,'api.github.com',Path1,_,_)),
 3273    setup_call_cleanup(
 3274      http_open(ApiUri, In,
 3275                [ request_header('Accept'='application/vnd.github.v3+json')
 3276                ]),
 3277      json_read_dict(In, Dicts),
 3278      close(In)),
 3279    member(Dict, Dicts),
 3280    atom_string(Tag, Dict.name),
 3281    tag_version(Tag, Version),
 3282    atom_string(VersionURI, Dict.zipball_url).
 3283
 3284wildcard_pattern(URL) :- sub_atom(URL, _, _, _, *).
 3285wildcard_pattern(URL) :- sub_atom(URL, _, _, _, ?).
 3286
 3287ensure_slash(Dir, DirS) :-
 3288    (   sub_atom(Dir, _, _, 0, /)
 3289    ->  DirS = Dir
 3290    ;   atom_concat(Dir, /, DirS)
 3291    ).
 3292
 3293remove_slash(Dir0, Dir) :-
 3294    Dir0 \== '/',
 3295    atom_concat(Dir1, /, Dir0),
 3296    !,
 3297    remove_slash(Dir1, Dir).
 3298remove_slash(Dir, Dir).
 3299
 3300absolute_matching_href(DOM, Pattern, Match) :-
 3301    xpath(DOM, //a(@href), HREF),
 3302    uri_normalized(HREF, Pattern, Match),
 3303    wildcard_match(Pattern, Match).
 3304
 3305versioned_urls([], []).
 3306versioned_urls([H|T0], List) :-
 3307    file_base_name(H, File),
 3308    (   pack_version_file(_Pack, Version, File)
 3309    ->  List = [Version-H|T]
 3310    ;   List = T
 3311    ),
 3312    versioned_urls(T0, T).
 3313
 3314
 3315                 /*******************************
 3316                 *          DEPENDENCIES        *
 3317                 *******************************/
 pack_provides(?Pack, -Provides) is multi
 pack_requires(?Pack, -Requires) is nondet
 pack_conflicts(?Pack, -Conflicts) is nondet
Provide logical access to pack dependency relations.
 3325pack_provides(Pack, Pack@Version) :-
 3326    current_pack(Pack),
 3327    once(pack_info(Pack, version, version(Version))).
 3328pack_provides(Pack, Provides) :-
 3329    findall(Prv, pack_info(Pack, dependency, provides(Prv)), PrvList),
 3330    member(Provides, PrvList).
 3331
 3332pack_requires(Pack, Requires) :-
 3333    current_pack(Pack),
 3334    findall(Req, pack_info(Pack, dependency, requires(Req)), ReqList),
 3335    member(Requires, ReqList).
 3336
 3337pack_conflicts(Pack, Conflicts) :-
 3338    current_pack(Pack),
 3339    findall(Cfl, pack_info(Pack, dependency, conflicts(Cfl)), CflList),
 3340    member(Conflicts, CflList).
 pack_depends_on(?Pack, ?Dependency) is nondet
True when Pack depends on pack Dependency. This predicate does not deal with transitive dependency.
 3347pack_depends_on(Pack, Dependency) :-
 3348    ground(Pack),
 3349    !,
 3350    pack_requires(Pack, Requires),
 3351    \+ is_prolog_token(Requires),
 3352    pack_provides(Dependency, Provides),
 3353    satisfies_req(Provides, Requires).
 3354pack_depends_on(Pack, Dependency) :-
 3355    ground(Dependency),
 3356    !,
 3357    pack_provides(Dependency, Provides),
 3358    pack_requires(Pack, Requires),
 3359    satisfies_req(Provides, Requires).
 3360pack_depends_on(Pack, Dependency) :-
 3361    current_pack(Pack),
 3362    pack_depends_on(Pack, Dependency).
 dependents(+Pack, -Dependents) is semidet
True when Dependents is a list of packs that (indirectly) depend on Pack.
 3369dependents(Pack, Deps) :-
 3370    setof(Dep, dependent(Pack, Dep, []), Deps).
 3371
 3372dependent(Pack, Dep, Seen) :-
 3373    pack_depends_on(Dep0, Pack),
 3374    \+ memberchk(Dep0, Seen),
 3375    (   Dep = Dep0
 3376    ;   dependent(Dep0, Dep, [Dep0|Seen])
 3377    ).
 validate_dependencies is det
Validate all dependencies, reporting on failures
 3383validate_dependencies :-
 3384    setof(Issue, pack_dependency_issue(_, Issue), Issues),
 3385    !,
 3386    print_message(warning, pack(dependency_issues(Issues))).
 3387validate_dependencies.
 pack_dependency_issue(?Pack, -Issue) is nondet
True when Issue is a dependency issue regarding Pack. Issue is one of
unsatisfied(Pack, Requires)
The requirement Requires of Pack is not fulfilled.
conflicts(Pack, Conflict)
Pack conflicts with Conflict.
 3399pack_dependency_issue(Pack, Issue) :-
 3400    current_pack(Pack),
 3401    pack_dependency_issue_(Pack, Issue).
 3402
 3403pack_dependency_issue_(Pack, unsatisfied(Pack, Requires)) :-
 3404    pack_requires(Pack, Requires),
 3405    (   is_prolog_token(Requires)
 3406    ->  \+ prolog_satisfies(Requires)
 3407    ;   \+ ( pack_provides(_, Provides),
 3408             satisfies_req(Provides, Requires) )
 3409    ).
 3410pack_dependency_issue_(Pack, conflicts(Pack, Conflicts)) :-
 3411    pack_conflicts(Pack, Conflicts),
 3412    (   is_prolog_token(Conflicts)
 3413    ->  prolog_satisfies(Conflicts)
 3414    ;   pack_provides(_, Provides),
 3415        satisfies_req(Provides, Conflicts)
 3416    ).
 3417
 3418
 3419		 /*******************************
 3420		 *      RECORD PACK FACTS	*
 3421		 *******************************/
 pack_assert(+PackDir, ++Fact) is det
Add/update a fact about packs. These facts are stored in PackDir/status.db. Known facts are:
built(Arch, Version, How)
Pack has been built by SWI-Prolog Version for Arch. How is one of built if we built it or downloaded if it was downloaded.
automatic(Boolean)
If true, pack was installed as dependency.
archive(Archive, URL)
Available when the pack was installed by unpacking Archive that was retrieved from URL.
 3437pack_assert(PackDir, Fact) :-
 3438    must_be(ground, Fact),
 3439    findall(Term, pack_status_dir(PackDir, Term), Facts0),
 3440    update_facts(Facts0, Fact, Facts),
 3441    OpenOptions = [encoding(utf8), lock(exclusive)],
 3442    status_file(PackDir, StatusFile),
 3443    (   Facts == Facts0
 3444    ->  true
 3445    ;   Facts0 \== [],
 3446        append(Facts0, New, Facts)
 3447    ->  setup_call_cleanup(
 3448            open(StatusFile, append, Out, OpenOptions),
 3449            maplist(write_fact(Out), New),
 3450            close(Out))
 3451    ;   setup_call_cleanup(
 3452            open(StatusFile, write, Out, OpenOptions),
 3453            ( write_facts_header(Out),
 3454              maplist(write_fact(Out), Facts)
 3455            ),
 3456            close(Out))
 3457    ).
 3458
 3459update_facts([], Fact, [Fact]) :-
 3460    !.
 3461update_facts([H|T], Fact, [Fact|T]) :-
 3462    general_pack_fact(Fact, GenFact),
 3463    general_pack_fact(H, GenTerm),
 3464    GenFact =@= GenTerm,
 3465    !.
 3466update_facts([H|T0], Fact, [H|T]) :-
 3467    update_facts(T0, Fact, T).
 3468
 3469general_pack_fact(built(Arch, _Version, _How), General) =>
 3470    General = built(Arch, _, _).
 3471general_pack_fact(Term, General), compound(Term) =>
 3472    compound_name_arity(Term, Name, Arity),
 3473    compound_name_arity(General, Name, Arity).
 3474general_pack_fact(Term, General) =>
 3475    General = Term.
 3476
 3477write_facts_header(Out) :-
 3478    format(Out, '% Fact status file.  Managed by package manager.~n', []).
 3479
 3480write_fact(Out, Term) :-
 3481    format(Out, '~q.~n', [Term]).
 pack_status(?Pack, ?Fact)
 pack_status_dir(+PackDir, ?Fact)
True when Fact is true about the package in PackDir. Facts are asserted a file status.db.
 3489pack_status(Pack, Fact) :-
 3490    current_pack(Pack, PackDir),
 3491    pack_status_dir(PackDir, Fact).
 3492
 3493pack_status_dir(PackDir, Fact) :-
 3494    det_if(ground(Fact), pack_status_(PackDir, Fact)).
 3495
 3496pack_status_(PackDir, Fact) :-
 3497    status_file(PackDir, StatusFile),
 3498    catch(term_in_file(valid_term(pack_status_term), StatusFile, Fact),
 3499          error(existence_error(source_sink, StatusFile), _),
 3500          fail).
 3501
 3502pack_status_term(built(atom, version, oneof([built,downloaded]))).
 3503pack_status_term(automatic(boolean)).
 3504pack_status_term(archive(atom, atom)).
 update_automatic(+Info) is det
Update the automatic status of a package. If we install it has no automatic status and we install it as a dependency we mark it as automatic. Else, we mark it as non-automatic as it has been installed explicitly.
 3514update_automatic(Info) :-
 3515    _ = Info.get(dependency_for),
 3516    \+ pack_status(Info.installed, automatic(_)),
 3517    !,
 3518    pack_assert(Info.installed, automatic(true)).
 3519update_automatic(Info) :-
 3520    pack_assert(Info.installed, automatic(false)).
 3521
 3522status_file(PackDir, StatusFile) :-
 3523    directory_file_path(PackDir, 'status.db', StatusFile).
 3524
 3525                 /*******************************
 3526                 *        USER INTERACTION      *
 3527                 *******************************/
 3528
 3529:- multifile prolog:message//1.
 menu(Question, +Alternatives, +Default, -Selection, +Options)
 3533menu(_Question, _Alternatives, Default, Selection, Options) :-
 3534    option(interactive(false), Options),
 3535    !,
 3536    Selection = Default.
 3537menu(Question, Alternatives, Default, Selection, _) :-
 3538    length(Alternatives, N),
 3539    between(1, 5, _),
 3540       print_message(query, Question),
 3541       print_menu(Alternatives, Default, 1),
 3542       print_message(query, pack(menu(select))),
 3543       read_selection(N, Choice),
 3544    !,
 3545    (   Choice == default
 3546    ->  Selection = Default
 3547    ;   nth1(Choice, Alternatives, Selection=_)
 3548    ->  true
 3549    ).
 3550
 3551print_menu([], _, _).
 3552print_menu([Value=Label|T], Default, I) :-
 3553    (   Value == Default
 3554    ->  print_message(query, pack(menu(default_item(I, Label))))
 3555    ;   print_message(query, pack(menu(item(I, Label))))
 3556    ),
 3557    I2 is I + 1,
 3558    print_menu(T, Default, I2).
 3559
 3560read_selection(Max, Choice) :-
 3561    get_single_char(Code),
 3562    (   answered_default(Code)
 3563    ->  Choice = default
 3564    ;   code_type(Code, digit(Choice)),
 3565        between(1, Max, Choice)
 3566    ->  true
 3567    ;   print_message(warning, pack(menu(reply(1,Max)))),
 3568        fail
 3569    ).
 confirm(+Question, +Default, +Options) is semidet
Ask for confirmation.
Arguments:
Default- is one of yes, no or none.
 3577confirm(_Question, Default, Options) :-
 3578    Default \== none,
 3579    option(interactive(false), Options, true),
 3580    !,
 3581    Default == yes.
 3582confirm(Question, Default, _) :-
 3583    between(1, 5, _),
 3584       print_message(query, pack(confirm(Question, Default))),
 3585       read_yes_no(YesNo, Default),
 3586    !,
 3587    format(user_error, '~N', []),
 3588    YesNo == yes.
 3589
 3590read_yes_no(YesNo, Default) :-
 3591    get_single_char(Code),
 3592    code_yes_no(Code, Default, YesNo),
 3593    !.
 3594
 3595code_yes_no(0'y, _, yes).
 3596code_yes_no(0'Y, _, yes).
 3597code_yes_no(0'n, _, no).
 3598code_yes_no(0'N, _, no).
 3599code_yes_no(_, none, _) :- !, fail.
 3600code_yes_no(C, Default, Default) :-
 3601    answered_default(C).
 3602
 3603answered_default(0'\r).
 3604answered_default(0'\n).
 3605answered_default(0'\s).
 3606
 3607
 3608                 /*******************************
 3609                 *            MESSAGES          *
 3610                 *******************************/
 3611
 3612:- multifile prolog:message//1. 3613
 3614prolog:message(pack(Message)) -->
 3615    message(Message).
 3616
 3617:- discontiguous
 3618    message//1,
 3619    label//1. 3620
 3621message(invalid_term(pack_info_term, Term)) -->
 3622    [ 'Invalid package meta data: ~q'-[Term] ].
 3623message(invalid_term(pack_status_term, Term)) -->
 3624    [ 'Invalid package status data: ~q'-[Term] ].
 3625message(directory_exists(Dir)) -->
 3626    [ 'Package target directory exists and is not empty:', nl,
 3627      '\t~q'-[Dir]
 3628    ].
 3629message(already_installed(pack(Pack, Version))) -->
 3630    [ 'Pack `~w'' is already installed @~w'-[Pack, Version] ].
 3631message(already_installed(Pack)) -->
 3632    [ 'Pack `~w'' is already installed. Package info:'-[Pack] ].
 3633message(kept_foreign(Pack, Arch)) -->
 3634    [ 'Found foreign libraries for architecture '-[],
 3635      ansi(code, '~q', [Arch]), nl,
 3636      'Use ', ansi(code, '?- pack_rebuild(~q).', [Pack]),
 3637      ' to rebuild from sources'-[]
 3638    ].
 3639message(no_pack_installed(Pack)) -->
 3640    [ 'No pack ~q installed.  Use ?- pack_list(Pattern) to search'-[Pack] ].
 3641message(dependency_issues(Issues)) -->
 3642    [ 'The current set of packs has dependency issues:', nl ],
 3643    dep_issues(Issues).
 3644message(depends(Pack, Deps)) -->
 3645    [ 'The following packs depend on `~w\':'-[Pack], nl ],
 3646    pack_list(Deps).
 3647message(remove(link(To), PackDir)) -->
 3648    [ 'Removing ', url(PackDir), nl, '    as link to ', url(To) ].
 3649message(remove(directory, PackDir)) -->
 3650    [ 'Removing ~q and contents'-[PackDir] ].
 3651message(hash_mismatch(Pack, URL, Expected, Hash)) -->
 3652    [ 'The archive for pack ~q downloaded from ~w'-[Pack, URL], nl,
 3653      'has SHA1 hash ~w, while the pack server expects ~w.'-[Hash, Expected], nl,
 3654      'The archive may have been modified.'
 3655    ].
 3656message(accept_hash_mismatch) -->
 3657    [ 'Install the pack anyway?' ].
 3658message(remove_existing_pack(PackDir)) -->
 3659    [ 'Remove old installation in ~q'-[PackDir] ].
 3660message(delete_autoload_index(Pack, Index)) -->
 3661    [ 'Pack ' ], msg_pack(Pack), [ ': deleting autoload index ', url(Index) ].
 3662message(download_plan(Plan)) -->
 3663    [ ansi(bold, 'Installation plan:', []), nl ],
 3664    install_plan(Plan, Actions),
 3665    install_label(Actions).
 3666message(build_plan(Plan)) -->
 3667    [ ansi(bold, 'The following packs have post install scripts:', []), nl ],
 3668    msg_build_plan(Plan),
 3669    [ nl, ansi(bold, 'Run scripts?', []) ].
 3670message(autoload(Pack)) -->
 3671    [ 'Pack ' ], msg_pack(Pack),
 3672    [ ' prefers to be added as autoload library',
 3673      nl, ansi(bold, 'Allow?', [])
 3674    ].
 3675message(no_meta_data(BaseDir)) -->
 3676    [ 'Cannot find pack.pl inside directory ~q.  Not a package?'-[BaseDir] ].
 3677message(search_no_matches(Name)) -->
 3678    [ 'Search for "~w", returned no matching packages'-[Name] ].
 3679message(rebuild(Pack)) -->
 3680    [ 'Checking pack "~w" for rebuild ...'-[Pack] ].
 3681message(up_to_date([Pack])) -->
 3682    !,
 3683    [ 'Pack ' ], msg_pack(Pack), [' is up-to-date' ].
 3684message(up_to_date(Packs)) -->
 3685    [ 'Packs ' ], sequence(msg_pack, [', '], Packs), [' are up-to-date' ].
 3686message(installed_can_upgrade(List)) -->
 3687    sequence(msg_can_upgrade_target, [nl], List).
 3688message(new_dependencies(Deps)) -->
 3689    [ 'Found new dependencies after downloading (~p).'-[Deps], nl ].
 3690message(query_versions(URL)) -->
 3691    [ 'Querying "~w" to find new versions ...'-[URL] ].
 3692message(no_matching_urls(URL)) -->
 3693    [ 'Could not find any matching URL: ~q'-[URL] ].
 3694message(found_versions([Latest-_URL|More])) -->
 3695    { length(More, Len) },
 3696    [ '    Latest version: ~w (~D older)'-[Latest, Len] ].
 3697message(build(Pack, PackDir)) -->
 3698    [ ansi(bold, 'Building pack ~w in directory ~w', [Pack, PackDir]) ].
 3699message(contacting_server(Server)) -->
 3700    [ 'Contacting server at ~w ...'-[Server], flush ].
 3701message(server_reply(true(_))) -->
 3702    [ at_same_line, ' ok'-[] ].
 3703message(server_reply(false)) -->
 3704    [ at_same_line, ' done'-[] ].
 3705message(server_reply(exception(E))) -->
 3706    [ 'Server reported the following error:'-[], nl ],
 3707    '$messages':translate_message(E).
 3708message(cannot_create_dir(Alias)) -->
 3709    { findall(PackDir,
 3710              absolute_file_name(Alias, PackDir, [solutions(all)]),
 3711              PackDirs0),
 3712      sort(PackDirs0, PackDirs)
 3713    },
 3714    [ 'Cannot find a place to create a package directory.'-[],
 3715      'Considered:'-[]
 3716    ],
 3717    candidate_dirs(PackDirs).
 3718message(conflict(version, [PackV, FileV])) -->
 3719    ['Version mismatch: pack.pl: '-[]], msg_version(PackV),
 3720    [', file claims version '-[]], msg_version(FileV).
 3721message(conflict(name, [PackInfo, FileInfo])) -->
 3722    ['Pack ~w mismatch: pack.pl: ~p'-[PackInfo]],
 3723    [', file claims ~w: ~p'-[FileInfo]].
 3724message(no_prolog_response(ContentType, String)) -->
 3725    [ 'Expected Prolog response.  Got content of type ~p'-[ContentType], nl,
 3726      '~s'-[String]
 3727    ].
 3728message(download(begin, Pack, _URL, _DownloadFile)) -->
 3729    [ 'Downloading ' ], msg_pack(Pack), [ ' ... ', flush ].
 3730message(download(end, _, _, File)) -->
 3731    { size_file(File, Bytes) },
 3732    [ at_same_line, '~D bytes'-[Bytes] ].
 3733message(no_git(URL)) -->
 3734    [ 'Cannot install from git repository ', url(URL), '.', nl,
 3735      'Cannot find git program and do not know how to download the code', nl,
 3736      'from this git service.  Please install git and retry.'
 3737    ].
 3738message(git_no_https(GitURL)) -->
 3739    [ 'Do not know how to get an HTTP(s) URL for ', url(GitURL) ].
 3740message(git_branch_not_default(Dir, Default, Current)) -->
 3741    [ 'GIT current branch on ', url(Dir), ' is not default.', nl,
 3742      '  Current branch: ', ansi(code, '~w', [Current]),
 3743      ' default: ', ansi(code, '~w', [Default])
 3744    ].
 3745message(git_not_clean(Dir)) -->
 3746    [ 'GIT working directory is dirty: ', url(Dir), nl,
 3747      'Your repository must be clean before publishing.'
 3748    ].
 3749message(git_push) -->
 3750    [ 'Push release to GIT origin?' ].
 3751message(git_tag(Tag)) -->
 3752    [ 'Tag repository with release tag ', ansi(code, '~w', [Tag]) ].
 3753message(git_release_tag_not_at_head(Tag)) -->
 3754    [ 'Release tag ', ansi(code, '~w', [Tag]), ' is not at HEAD.', nl,
 3755      'If you want to update the tag, please run ',
 3756      ansi(code, 'git tag -d ~w', [Tag])
 3757    ].
 3758message(git_tag_out_of_sync(Tag)) -->
 3759    [ 'Release tag ', ansi(code, '~w', [Tag]),
 3760      ' differs from this tag at the origin'
 3761    ].
 3762
 3763message(published(Info, At)) -->
 3764    [ 'Published pack ' ], msg_pack(Info), msg_info_version(Info),
 3765    [' to be installed from '],
 3766    msg_published_address(At).
 3767message(publish_failed(Info, Reason)) -->
 3768    [ 'Pack ' ], msg_pack(Info), [ ' at version ~w'-[Info.version] ],
 3769    msg_publish_failed(Reason).
 3770
 3771msg_publish_failed(throw(error(permission_error(register,
 3772                                                pack(_),_URL),_))) -->
 3773    [ ' is already registered with a different URL'].
 3774msg_publish_failed(download) -->
 3775    [' was already published?'].
 3776msg_publish_failed(Status) -->
 3777    [ ' failed for unknown reason (~p)'-[Status] ].
 3778
 3779msg_published_address(git(URL)) -->
 3780    msg_url(URL, _).
 3781msg_published_address(file(URL)) -->
 3782    msg_url(URL, _).
 3783
 3784candidate_dirs([]) --> [].
 3785candidate_dirs([H|T]) --> [ nl, '    ~w'-[H] ], candidate_dirs(T).
 3786                                                % Questions
 3787message(resolve_remove) -->
 3788    [ nl, 'Please select an action:', nl, nl ].
 3789message(create_pack_dir) -->
 3790    [ nl, 'Create directory for packages', nl ].
 3791message(menu(item(I, Label))) -->
 3792    [ '~t(~d)~6|   '-[I] ],
 3793    label(Label).
 3794message(menu(default_item(I, Label))) -->
 3795    [ '~t(~d)~6| * '-[I] ],
 3796    label(Label).
 3797message(menu(select)) -->
 3798    [ nl, 'Your choice? ', flush ].
 3799message(confirm(Question, Default)) -->
 3800    message(Question),
 3801    confirm_default(Default),
 3802    [ flush ].
 3803message(menu(reply(Min,Max))) -->
 3804    (  { Max =:= Min+1 }
 3805    -> [ 'Please enter ~w or ~w'-[Min,Max] ]
 3806    ;  [ 'Please enter a number between ~w and ~w'-[Min,Max] ]
 3807    ).
 3808
 3809                                                % support predicates
 3810dep_issues(Issues) -->
 3811    sequence(dep_issue, [nl], Issues).
 3812
 3813dep_issue(unsatisfied(Pack, Requires)) -->
 3814    [ ' - Pack ' ], msg_pack(Pack), [' requires ~p'-[Requires]].
 3815dep_issue(conflicts(Pack, Conflict)) -->
 3816    [ ' - Pack ' ], msg_pack(Pack), [' conflicts with ~p'-[Conflict]].
 install_plan(+Plan, -Actions)// is det
 install_label(+Actions)// is det
Describe the overall installation plan before downloading.
 3823install_label([link]) -->
 3824    !,
 3825    [ ansi(bold, 'Activate pack?', []) ].
 3826install_label([unpack]) -->
 3827    !,
 3828    [ ansi(bold, 'Unpack archive?', []) ].
 3829install_label(_) -->
 3830    [ ansi(bold, 'Download packs?', []) ].
 3831
 3832
 3833install_plan(Plan, Actions) -->
 3834    install_plan(Plan, Actions, Sec),
 3835    sec_warning(Sec).
 3836
 3837install_plan([], [], _) -->
 3838    [].
 3839install_plan([H|T], [AH|AT], Sec) -->
 3840    install_step(H, AH, Sec), [nl],
 3841    install_plan(T, AT, Sec).
 3842
 3843install_step(Info, keep, _Sec) -->
 3844    { Info.get(keep) == true },
 3845    !,
 3846    [ '  Keep ' ], msg_pack(Info), [ ' at version ~w'-[Info.version] ],
 3847    msg_can_upgrade(Info).
 3848install_step(Info, Action, Sec) -->
 3849    { From = Info.get(upgrade),
 3850      VFrom = From.version,
 3851      VTo = Info.get(version),
 3852      (   cmp_versions(>=, VTo, VFrom)
 3853      ->  Label = ansi(bold,    '  Upgrade ',   [])
 3854      ;   Label = ansi(warning, '  Downgrade ', [])
 3855      )
 3856    },
 3857    [ Label ], msg_pack(Info),
 3858    [ ' from version ~w to ~w'- [From.version, Info.get(version)] ],
 3859    install_from(Info, Action, Sec).
 3860install_step(Info, Action, Sec) -->
 3861    { _From = Info.get(upgrade) },
 3862    [ '  Upgrade '  ], msg_pack(Info),
 3863    install_from(Info, Action, Sec).
 3864install_step(Info, Action, Sec) -->
 3865    { Dep = Info.get(dependency_for) },
 3866    [ '  Install ' ], msg_pack(Info),
 3867    [ ' at version ~w as dependency for '-[Info.version],
 3868      ansi(code, '~w', [Dep])
 3869    ],
 3870    install_from(Info, Action, Sec),
 3871    msg_downloads(Info).
 3872install_step(Info, Action, Sec) -->
 3873    { Info.get(commit) == 'HEAD' },
 3874    !,
 3875    [ '  Install ' ], msg_pack(Info), [ ' at current GIT HEAD'-[] ],
 3876    install_from(Info, Action, Sec),
 3877    msg_downloads(Info).
 3878install_step(Info, link, _Sec) -->
 3879    { Info.get(link) == true,
 3880      uri_file_name(Info.get(url), Dir)
 3881    },
 3882    !,
 3883    [ '  Install ' ], msg_pack(Info), [ ' as symlink to ', url(Dir) ].
 3884install_step(Info, Action, Sec) -->
 3885    [ '  Install ' ], msg_pack(Info), [ ' at version ~w'-[Info.get(version)] ],
 3886    install_from(Info, Action, Sec),
 3887    msg_downloads(Info).
 3888install_step(Info, Action, Sec) -->
 3889    [ '  Install ' ], msg_pack(Info),
 3890    install_from(Info, Action, Sec),
 3891    msg_downloads(Info).
 3892
 3893install_from(Info, download, Sec) -->
 3894    { download_url(Info.url) },
 3895    !,
 3896    [ ' from '  ], msg_url(Info.url, Sec).
 3897install_from(Info, unpack, Sec) -->
 3898    [ ' from '  ], msg_url(Info.url, Sec).
 3899
 3900msg_url(URL, unsafe) -->
 3901    { atomic(URL),
 3902      atom_concat('http://', Rest, URL)
 3903    },
 3904    [ ansi(error, '~w', ['http://']), '~w'-[Rest] ].
 3905msg_url(URL, _) -->
 3906    [ url(URL) ].
 3907
 3908sec_warning(Sec) -->
 3909    { var(Sec) },
 3910    !.
 3911sec_warning(unsafe) -->
 3912    [ ansi(warning, '  WARNING: The installation plan includes downloads \c
 3913                                from insecure HTTP servers.', []), nl
 3914    ].
 3915
 3916msg_downloads(Info) -->
 3917    { Downloads = Info.get(all_downloads),
 3918      Downloads > 0
 3919    },
 3920    [ ansi(comment, ' (downloaded ~D times)', [Downloads]) ],
 3921    !.
 3922msg_downloads(_) -->
 3923    [].
 3924
 3925msg_pack(Pack) -->
 3926    { atom(Pack) },
 3927    !,
 3928    [ ansi(code, '~w', [Pack]) ].
 3929msg_pack(Info) -->
 3930    msg_pack(Info.pack).
 3931
 3932msg_info_version(Info) -->
 3933    [ ansi(code, '@~w', [Info.get(version)]) ],
 3934    !.
 3935msg_info_version(_Info) -->
 3936    [].
 msg_build_plan(+Plan)//
Describe the build plan before running the build steps.
 3942msg_build_plan(Plan) -->
 3943    sequence(build_step, [nl], Plan).
 3944
 3945build_step(Info) -->
 3946    [ '  Build ' ], msg_pack(Info), [' in directory ', url(Info.installed) ].
 3947
 3948msg_can_upgrade_target(Info) -->
 3949    [ '  Pack ' ], msg_pack(Info),
 3950    [ ' is installed at version ~w'-[Info.version] ],
 3951    msg_can_upgrade(Info).
 3952
 3953pack_list([]) --> [].
 3954pack_list([H|T]) -->
 3955    [ '    - Pack ' ],  msg_pack(H), [nl],
 3956    pack_list(T).
 3957
 3958label(remove_only(Pack)) -->
 3959    [ 'Only remove package ~w (break dependencies)'-[Pack] ].
 3960label(remove_deps(Pack, Deps)) -->
 3961    { length(Deps, Count) },
 3962    [ 'Remove package ~w and ~D dependencies'-[Pack, Count] ].
 3963label(create_dir(Dir)) -->
 3964    [ '~w'-[Dir] ].
 3965label(install_from(git(URL))) -->
 3966    !,
 3967    [ 'GIT repository at ~w'-[URL] ].
 3968label(install_from(URL)) -->
 3969    [ '~w'-[URL] ].
 3970label(cancel) -->
 3971    [ 'Cancel' ].
 3972
 3973confirm_default(yes) -->
 3974    [ ' Y/n? ' ].
 3975confirm_default(no) -->
 3976    [ ' y/N? ' ].
 3977confirm_default(none) -->
 3978    [ ' y/n? ' ].
 3979
 3980msg_version(Version) -->
 3981    [ '~w'-[Version] ].
 3982
 3983msg_can_upgrade(Info) -->
 3984    { Latest = Info.get(latest_version) },
 3985    [ ansi(warning, ' (can be upgraded to ~w)', [Latest]) ].
 3986msg_can_upgrade(_) -->
 3987    [].
 3988
 3989
 3990		 /*******************************
 3991		 *              MISC		*
 3992		 *******************************/
 3993
 3994local_uri_file_name(URL, FileName) :-
 3995    uri_file_name(URL, FileName),
 3996    !.
 3997local_uri_file_name(URL, FileName) :-
 3998    uri_components(URL, Components),
 3999    uri_data(scheme, Components, File), File == file,
 4000    uri_data(authority, Components, FileNameEnc),
 4001    uri_data(path, Components, ''),
 4002    uri_encoded(path, FileName, FileNameEnc).
 4003
 4004det_if(Cond, Goal) :-
 4005    (   Cond
 4006    ->  Goal,
 4007        !
 4008    ;   Goal
 4009    ).
 4010
 4011member_nonvar(_, Var) :-
 4012    var(Var),
 4013    !,
 4014    fail.
 4015member_nonvar(E, [E|_]).
 4016member_nonvar(E, [_|T]) :-
 4017    member_nonvar(E, T)