File: tools.pl

package info (click to toggle)
swi-prolog 9.2.9%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 84,456 kB
  • sloc: ansic: 401,705; perl: 374,799; lisp: 9,080; cpp: 8,920; java: 5,525; sh: 3,282; javascript: 2,690; python: 2,655; ruby: 1,594; yacc: 845; makefile: 440; xml: 317; sed: 12; sql: 6
file content (825 lines) | stat: -rw-r--r-- 27,859 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        jan@swi-prolog.org
    WWW:           https://www.swi-prolog.org
    Copyright (c)  2021-2024, SWI-Prolog Solutions b.v.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

:- module(build_tools,
	  [ build_steps/3,              % +Steps, +SrcDir, +Options
	    prolog_install_prefix/1,    % -Prefix
	    run_process/3,              % +Executable, +Argv, +Options
	    has_program/3,              % +Spec, -Path, +Env
	    ensure_build_dir/3          % +Dir, +State0, -State
	  ]).
:- autoload(library(lists), [selectchk/3, member/2, append/3, last/2]).
:- autoload(library(option), [option/2, option/3, dict_options/2]).
:- autoload(library(pairs), [pairs_values/2]).
:- autoload(library(process), [process_create/3, process_wait/2]).
:- autoload(library(readutil), [read_stream_to_codes/3]).
:- autoload(library(dcg/basics), [string/3]).
:- autoload(library(apply), [foldl/4, maplist/2]).
:- autoload(library(filesex), [directory_file_path/3, make_directory_path/1]).
:- autoload(library(prolog_config), [prolog_config/2]).
:- autoload(library(solution_sequences), [distinct/2]).

% The plugins.  Load them in the order of preference.
:- use_module(conan).
:- use_module(cmake).
:- use_module(make).

:- multifile
    prolog:build_file/2,                % ?File, ?Toolchain
    prolog:build_step/4,                % ?Step, ?Tool, ?SrcDir, ?BuildDir
    prolog:build_environment/2,         % ?Name, ?Value
    prolog_pack:environment/2.          % ?Name, ?Value (backward compatibility)

/** <module> Utilities for building foreign resources

This module implements the build system   that is used by pack_install/1
and pack_rebuild/1. The build system is a plugin based system where each
plugin knows about a specific  build   toolchain.  The plugins recognise
whether they are applicable based on  the   existence  of files that are
unique to the toolchain.   Currently it supports

  - [conan](https://conan.io/) for the installation of dependencies
  - [cmake](https://cmake.org/) for configuration and building
  - [GNU tools](https://www.gnu.org) including `automake` and `autoconf`
    for configuration and building
*/

%!  build_steps(+Steps:list, SrcDir:atom, +Options) is det.
%
%   Run the desired build steps.  Normally,   Steps  is  the list below,
%   optionally prefixed with `distclean` or `clean`. `[test]` may be
%   omited if ``--no-test`` is effective.
%
%       [[dependencies], [configure], build, [test], install]
%
%   Each step finds an applicable toolchain  based on known unique files
%   and calls the matching plugin to perform  the step. A step may fail,
%   which causes the system to try an  alternative. A step that wants to
%   abort the build process must  throw  an   exception.
%
%   If a step fails, a warning message is printed. The message can be
%   suppressed by enclosing the step in square brackets.  Thus, in the
%   above example of Steps, only failure  by the `build` and `install`
%   steps result in warning messages; failure of the other steps is
%   silent.
%
%   The failure of a step can be made into an error by enclosing it
%   in curly brackets, e.g. `[[dependencies], [configure], {build}, [test], {install}]`
%   would throw an exception if either the `build` or `install` step failed.
%
%   Options are:
%   * pack_version(N)
%     where N is 1 or 2 (default: 1).
%     This determines the form of environment names that are set before
%     the  build tools are calledd.
%     For version 1, names such as `SWIPLVERSION` or `SWIHOME` are used.
%     For version 2, names such as `SWIPL_VERSION` or `SWIPL_HOME_DIR` are used.
%
%   @tbd If no tool  is  willing  to   execute  some  step,  the step is
%   skipped. This is ok for some steps such as `dependencies` or `test`.
%   Possibly we should force the `install` step to succeed?

build_steps(Steps, SrcDir, Options) :-
    dict_options(Dict0, Options),
    setup_path,
    build_environment(BuildEnv, Options),
    State0 = Dict0.put(#{ env: BuildEnv,
			  src_dir: SrcDir
			}),

    foldl(build_step, Steps, State0, _State).

build_step(Spec, State0, State) :-
    build_step_(Spec, State0, State),
    post_step(Spec, State).

build_step_(Spec, State0, State) :-
    step_name(Spec, Step),
    prolog:build_file(File, Tool),
    directory_file_path(State0.src_dir, File, Path),
    exists_file(Path),
    prolog:build_step(Step, Tool, State0, State),
    !.
build_step_([_], State, State) :-
    !.
build_step_({Step}, State, State) :-
    !,
    print_message(error, build(step_failed(Step))),
    throw(error(build(step_failed(Step)))).
build_step_(Step, State, State) :-
    print_message(warning, build(step_failed(Step))).

step_name([Step], Name) => Name = Step.
step_name({Step}, Name) => Name = Step.
step_name(Step,   Name) => Name = Step.

%!  post_step(+Step, +State) is det.
%
%   Run code after completion of a step.

post_step(Step, State) :-
    step_name(Step, configure),
    !,
    save_build_environment(State).
post_step(_, _).


%!  ensure_build_dir(+Dir, +State0, -State) is det.
%
%   Create the build directory. Dir is normally   either '.' to build in
%   the source directory or `build` to create a `build` subdir.

ensure_build_dir(_, State0, State) :-
    _ = State0.get(bin_dir),
    !,
    State = State0.
ensure_build_dir(., State0, State) :-
    !,
    State = State0.put(bin_dir, State0.src_dir).
ensure_build_dir(Dir, State0, State) :-
    directory_file_path(State0.src_dir, Dir, BinDir),
    make_directory_path(BinDir),
    !,
    State = State0.put(bin_dir, BinDir).


		 /*******************************
		 *          ENVIRONMENT		*
		 *******************************/

%!  build_environment(-Env, +Options) is det.
%
%   Options are documented under build_steps/3.
%
%   Assemble a clean  build  environment   for  creating  extensions  to
%   SWI-Prolog. Env is a list of   `Var=Value` pairs. The variable names
%   depend on the `pack_version(Version)`  term   from  `pack.pl`.  When
%   absent or `1`, the old names are used. These names are confusing and
%   conflict with some build environments. Using `2` (or later), the new
%   names are used. The list below  first   names  the new name and than
%   between parenthesis, the old name.  Provided variables are:
%
%     $ ``PATH`` :
%     contains the environment path with the directory
%     holding the currently running SWI-Prolog instance prepended
%     in front of it.  As a result, `swipl` is always present and
%     runs the same SWI-Prolog instance as the current Prolog process.
%     $ ``SWIPL`` :
%     contains the absolute file name of the running executable.
%     $ ``SWIPL_PACK_VERSION`` :
%     Version of the pack system (1 or 2)
%     $ ``SWIPL_VERSION`` (``SWIPLVERSION``) :
%     contains the numeric SWI-Prolog version defined as
%     _|Major*10000+Minor*100+Patch|_.
%     $ ``SWIPL_HOME_DIR`` (``SWIHOME``) :
%     contains the directory holding the SWI-Prolog home.
%     $ ``SWIPL_ARCH`` (``SWIARCH``) :
%     contains the machine architecture identifier.
%     $ ``SWIPL_MODULE_DIR`` (``PACKSODIR``) :
%     constains the destination directory for shared objects/DLLs
%     relative to a Prolog pack, i.e., ``lib/$SWIARCH``.
%     $ ``SWIPL_MODULE_LIB`` (``SWISOLIB``) :
%     The SWI-Prolog library or an empty string when it is not required
%     to link modules against this library (e.g., ELF systems)
%     $ ``SWIPL_LIB`` (``SWILIB``) :
%     The SWI-Prolog library we need to link to for programs that
%     _embed_ SWI-Prolog (normally ``-lswipl``).
%     $ ``SWIPL_INCLUDE_DIRS`` :
%     CMake style variable that contains the directory holding
%     ``SWI-Prolog.h``, ``SWI-Stream.h`` and ``SWI-cpp.h``.
%     $ ``SWIPL_LIBRARIES_DIR`` :
%     CMake style variable that contains the directory holding `libswipl`
%     $ ``SWIPL_CC`` (``CC``) :
%     Prefered C compiler
%     $ ``SWIPL_CXX`` (``CXX``) :
%     Prefered C++ compiler
%     $ ``SWIPL_LD`` (``LD``) :
%     Prefered linker
%     $ ``SWIPL_CFLAGS`` (``CFLAGS``) :
%     C-Flags for building extensions. Always contains ``-ISWIPL-INCLUDE-DIR``.
%     $ ``SWIPL_MODULE_LDFLAGS`` (``LDSOFLAGS``) :
%     Link flags for linking modules.
%     $ ``SWIPL_MODULE_EXT`` (``SOEXT``) :
%     File name extension for modules (e.g., `so` or `dll`)
%     $ ``SWIPL_PREFIX`` (``PREFIX``) :
%     Install prefix for global binaries, libraries and include files.

build_environment(Env, Options) :-
    findall(Name=Value,
	    distinct(Name, user_environment(Name, Value)),
	    UserEnv),
    findall(Name=Value,
	    ( def_environment(Name, Value, Options),
	      \+ memberchk(Name=_, UserEnv)
	    ),
	    DefEnv),
    append(UserEnv, DefEnv, Env).

user_environment(Name, Value) :-
    prolog:build_environment(Name, Value).
user_environment(Name, Value) :-
    prolog_pack:environment(Name, Value).

%!  prolog:build_environment(-Name, -Value) is nondet.
%
%   Hook  to  define  the  environment   for  building  packs.  This
%   Multifile hook extends the  process   environment  for  building
%   foreign extensions. A value  provided   by  this  hook overrules
%   defaults provided by def_environment/3. In  addition to changing
%   the environment, this may be used   to pass additional values to
%   the environment, as in:
%
%     ==
%     prolog:build_environment('USER', User) :-
%         getenv('USER', User).
%     ==
%
%   @arg Name is an atom denoting a valid variable name
%   @arg Value is either an atom or number representing the
%          value of the variable.


%!  def_environment(-Name, -Value, +Options) is nondet.
%
%   True if Name=Value must appear in   the environment for building
%   foreign extensions.

def_environment('PATH', Value, _) :-
    getenv('PATH', PATH),
    current_prolog_flag(executable, Exe),
    file_directory_name(Exe, ExeDir),
    prolog_to_os_filename(ExeDir, OsExeDir),
    current_prolog_flag(path_sep, Sep),
    atomic_list_concat([OsExeDir, Sep, PATH], Value).
def_environment('SWIPL', Value, _) :-
    current_prolog_flag(executable, Value).
def_environment('SWIPL_PACK_VERSION', Value, Options) :-
    option(pack_version(Value), Options, 1).
def_environment('SWIPL_PACK_PATH', Value, _Options) :-
    prolog_config(pack_path, Value).
def_environment(VAR, Value, Options) :-
    env_name(version, VAR, Options),
    current_prolog_flag(version, Value).
def_environment(VAR, Value, Options) :-
    env_name(home, VAR, Options),
    current_prolog_flag(home, Value).
def_environment(VAR, Value, Options) :-
    env_name(arch, VAR, Options),
    current_prolog_flag(arch, Value).
def_environment(VAR, Value, Options) :-
    env_name(module_dir, VAR, Options),
    current_prolog_flag(arch, Arch),
    atom_concat('lib/', Arch, Value).
def_environment(VAR, Value, Options) :-
    env_name(module_lib, VAR, Options),
    current_prolog_flag(c_libplso, Value).
def_environment(VAR, '-lswipl', Options) :-
    env_name(lib, VAR, Options).
def_environment(VAR, Value, Options) :-
    env_name(cc, VAR, Options),
    default_c_compiler(Value).
def_environment(VAR, Value, Options) :-
    env_name(cxx, VAR, Options),
    default_cxx_compiler(Value).
def_environment(VAR, Value, Options) :-
    env_name(ld, VAR, Options),
    (   getenv('LD', Value)
    ->  true
    ;   default_c_compiler(Value)
    ).
def_environment('SWIPL_INCLUDE_DIRS', Value, _) :- % CMake style environment
    current_prolog_flag(home, Home),
    atom_concat(Home, '/include', Value).
def_environment('SWIPL_LIBRARIES_DIR', Value, _) :-
    swipl_libraries_dir(Value).
def_environment(VAR, Value, Options) :-
    env_name(cflags, VAR, Options),
    (   getenv('CFLAGS', SystemFlags)
    ->  Extra = [' ', SystemFlags]
    ;   Extra = []
    ),
    current_prolog_flag(c_cflags, Value0),
    current_prolog_flag(home, Home),
    atomic_list_concat([Value0, ' -I"', Home, '/include"' | Extra], Value).
def_environment(VAR, Value, Options) :-
    env_name(module_ldflags, VAR, Options),
    (   getenv('LDFLAGS', SystemFlags)
    ->  Extra = [SystemFlags|System]
    ;   Extra = System
    ),
    (   current_prolog_flag(windows, true)
    ->  prolog_library_dir(LibDir),
	atomic_list_concat(['-L"', LibDir, '"'], SystemLib),
	System = [SystemLib]
    ;   prolog_config(apple_bundle_libdir, LibDir)
    ->  atomic_list_concat(['-L"', LibDir, '"'], SystemLib),
	System = [SystemLib]
    ;   current_prolog_flag(c_libplso, '')
    ->  System = []                 % ELF systems do not need this
    ;   prolog_library_dir(SystemLibDir),
	atomic_list_concat(['-L"',SystemLibDir,'"'], SystemLib),
	System = [SystemLib]
    ),
    current_prolog_flag(c_ldflags, LDFlags),
    atomic_list_concat([LDFlags, '-shared' | Extra], ' ', Value).
def_environment(VAR, Value, Options) :-
    env_name(module_ext, VAR, Options),
    current_prolog_flag(shared_object_extension, Value).
def_environment(VAR, Value, Options) :-
    env_name(prefix, VAR, Options),
    prolog_install_prefix(Value).

swipl_libraries_dir(Dir) :-
    current_prolog_flag(windows, true),
    !,
    current_prolog_flag(home, Home),
    atom_concat(Home, '/bin', Dir).
swipl_libraries_dir(Dir) :-
    prolog_config(apple_bundle_libdir, Dir),
    !.
swipl_libraries_dir(Dir) :-
    prolog_library_dir(Dir).

env_name(Id, Name, Options) :-
    option(pack_version(V), Options, 1),
    must_be(oneof([1,2]), V),
    env_name_v(Id, V, Name).

env_name_v(version,        1, 'SWIPLVERSION').
env_name_v(version,        2, 'SWIPL_VERSION').
env_name_v(home,           1, 'SWIHOME').
env_name_v(home,           2, 'SWIPL_HOME_DIR').
env_name_v(module_dir,     1, 'PACKSODIR').
env_name_v(module_dir,     2, 'SWIPL_MODULE_DIR').
env_name_v(module_lib,     1, 'SWISOLIB').
env_name_v(module_lib,     2, 'SWIPL_MODULE_LIB').
env_name_v(lib,            1, 'SWILIB').
env_name_v(lib,            2, 'SWIPL_LIB').
env_name_v(arch,           1, 'SWIARCH').
env_name_v(arch,           2, 'SWIPL_ARCH').
env_name_v(cc,             1, 'CC').
env_name_v(cc,             2, 'SWIPL_CC').
env_name_v(cxx,            1, 'CXX').
env_name_v(cxx,            2, 'SWIPL_CXX').
env_name_v(ld,             1, 'LD').
env_name_v(ld,             2, 'SWIPL_LD').
env_name_v(cflags,         1, 'CFLAGS').
env_name_v(cflags,         2, 'SWIPL_CFLAGS').
env_name_v(module_ldflags, 1, 'LDSOFLAGS').
env_name_v(module_ldflags, 2, 'SWIPL_MODULE_LDFLAGS').
env_name_v(module_ext,     1, 'SOEXT').
env_name_v(module_ext,     2, 'SWIPL_MODULE_EXT').
env_name_v(prefix,         1, 'PREFIX').
env_name_v(prefix,         2, 'SWIPL_PREFIX').

%!  prolog_library_dir(-Dir) is det.
%
%   True when Dir is the directory holding ``libswipl.$SOEXT``

:- multifile
    prolog:runtime_config/2.

prolog_library_dir(Dir) :-
    prolog:runtime_config(c_libdir, Dir),
    !.
prolog_library_dir(Dir) :-
    current_prolog_flag(windows, true),
    \+ current_prolog_flag(msys2, true),
    current_prolog_flag(home, Home),
    !,
    atomic_list_concat([Home, bin], /, Dir).
prolog_library_dir(Dir) :-
    current_prolog_flag(home, Home),
    (   current_prolog_flag(c_libdir, Rel)
    ->  atomic_list_concat([Home, Rel], /, Dir)
    ;   current_prolog_flag(arch, Arch)
    ->  atomic_list_concat([Home, lib, Arch], /, Dir)
    ).

%!  default_c_compiler(-CC) is semidet.
%
%   Try to find a  suitable  C   compiler  for  compiling  packages with
%   foreign code.
%
%   @tbd Needs proper defaults for Windows.  Find MinGW?  Find MSVC?

default_c_compiler(CC) :-
    getenv('CC', CC),
    !.
default_c_compiler(CC) :-
    preferred_c_compiler(CC0),
    has_program(CC0, CC),
    !.

default_cxx_compiler(CXX) :-
    getenv('CXX', CXX),
    !.
default_cxx_compiler(CXX) :-
    preferred_cxx_compiler(CXX0),
    has_program(CXX0, CXX),
    !.

preferred_c_compiler(CC) :-
    current_prolog_flag(c_cc, CC).
preferred_c_compiler(gcc).
preferred_c_compiler(clang).
preferred_c_compiler(cc).

preferred_cxx_compiler(CXX) :-
    current_prolog_flag(c_cxx, CXX).
preferred_cxx_compiler('g++').
preferred_cxx_compiler('clang++').
preferred_cxx_compiler('c++').


%!  save_build_environment(+State:dict) is det.
%
%   Create  a  shell-script  ``buildenv.sh``  that  contains  the  build
%   environment. This may be _sourced_ in the build directory to run the
%   build steps outside Prolog. It  may   also  be  useful for debugging
%   purposes.

:- det(save_build_environment/1).
save_build_environment(State) :-
    Env = State.get(env),
    !,
    (   BuildDir = State.get(bin_dir)
    ->  true
    ;   BuildDir = State.get(src_dir)
    ),
    directory_file_path(BuildDir, 'buildenv.sh', EnvFile),
    setup_call_cleanup(
	open(EnvFile, write, Out),
	write_env_script(Out, Env),
	close(Out)).
save_build_environment(_).

write_env_script(Out, Env) :-
    format(Out,
	   '# This file contains the environment that can be used to\n\c
	    # build the foreign pack outside Prolog.  This file must\n\c
	    # be loaded into a bourne-compatible shell using\n\c
	    #\n\c
	    #   $ source buildenv.sh\n\n',
	   []),
    forall(member(Var=Value, Env),
	   format(Out, '~w=\'~w\'\n', [Var, Value])),
    format(Out, '\nexport ', []),
    forall(member(Var=_, Env),
	   format(Out, ' ~w', [Var])),
    format(Out, '\n', []).

%!  prolog_install_prefix(-Prefix) is semidet.
%
%   Return the directory that can be  passed into `configure` or `cmake`
%   to install executables and other  related   resources  in  a similar
%   location as SWI-Prolog itself.  Tries these rules:
%
%     1. If the Prolog flag `pack_prefix` at a writable directory, use
%        this.
%     2. If the current executable can be found on $PATH and the parent
%        of the directory of the executable is writable, use this.
%     3. If the user has a writable ``~/bin`` directory, use ``~``.

prolog_install_prefix(Prefix) :-
    current_prolog_flag(pack_prefix, Prefix),
    access_file(Prefix, write),
    !.
prolog_install_prefix(Prefix) :-
    current_prolog_flag(os_argv, [Name|_]),
    has_program(path(Name), EXE),
    file_directory_name(EXE, Bin),
    file_directory_name(Bin, Prefix0),
    (   local_prefix(Prefix0, Prefix1)
    ->  Prefix = Prefix1
    ;   Prefix = Prefix0
    ),
    access_file(Prefix, write),
    !.
prolog_install_prefix(Prefix) :-
    expand_file_name(~, [UserHome]),
    directory_file_path(UserHome, bin, BinDir),
    exists_directory(BinDir),
    access_file(BinDir, write),
    !,
    Prefix = UserHome.

local_prefix('/usr', '/usr/local').


		 /*******************************
		 *          RUN PROCESSES       *
		 *******************************/

%!  run_process(+Executable, +Argv, +Options) is det.
%
%   Run Executable.  Defined options:
%
%     - directory(+Dir)
%       Execute in the given directory
%     - output(-Out)
%       Unify Out with a list of codes representing stdout of the
%       command.  Otherwise the output is handed to print_message/2
%       with level =informational=.
%     - error(-Error)
%       As output(Out), but messages are printed at level =error=.
%     - env(+Environment)
%       Environment passed to the new process.
%
%   If Executable is path(Program) and we   have  an environment we make
%   sure to use  the  ``PATH``  from   this  environment  for  searching
%   `Program`.

run_process(path(Exe), Argv, Options) :-
    option(env(BuildEnv), Options),
    !,
    setup_call_cleanup(
	b_setval('$build_tool_env', BuildEnv),
	run_process(pack_build_path(Exe), Argv, Options),
	nb_delete('$build_tool_env')).
run_process(Executable, Argv, Options) :-
    \+ option(output(_), Options),
    \+ option(error(_), Options),
    current_prolog_flag(unix, true),
    current_prolog_flag(threads, true),
    !,
    process_create_options(Options, Extra),
    process_create(Executable, Argv,
		   [ stdout(pipe(Out)),
		     stderr(pipe(Error)),
		     process(PID)
		   | Extra
		   ]),
    thread_create(relay_output([output-Out, error-Error]), Id, []),
    process_wait(PID, Status),
    thread_join(Id, _),
    (   Status == exit(0)
    ->  true
    ;   throw(error(process_error(process(Executable, Argv), Status), _))
    ).
run_process(Executable, Argv, Options) :-
    process_create_options(Options, Extra),
    setup_call_cleanup(
	process_create(Executable, Argv,
		       [ stdout(pipe(Out)),
			 stderr(pipe(Error)),
			 process(PID)
		       | Extra
		       ]),
	(   read_stream_to_codes(Out, OutCodes, []),
	    read_stream_to_codes(Error, ErrorCodes, []),
	    process_wait(PID, Status)
	),
	(   close(Out),
	    close(Error)
	)),
    print_error(ErrorCodes, Options),
    print_output(OutCodes, Options),
    (   Status == exit(0)
    ->  true
    ;   throw(error(process_error(process(Executable, Argv), Status), _))
    ).

process_create_options(Options, Extra) :-
    option(directory(Dir), Options, .),
    (   option(env(Env), Options)
    ->  Extra = [cwd(Dir), environment(Env)]
    ;   Extra = [cwd(Dir)]
    ).

relay_output([]) :- !.
relay_output(Output) :-
    pairs_values(Output, Streams),
    wait_for_input(Streams, Ready, infinite),
    relay(Ready, Output, NewOutputs),
    relay_output(NewOutputs).

relay([], Outputs, Outputs).
relay([H|T], Outputs0, Outputs) :-
    selectchk(Type-H, Outputs0, Outputs1),
    (   at_end_of_stream(H)
    ->  close(H),
	relay(T, Outputs1, Outputs)
    ;   read_pending_codes(H, Codes, []),
	relay(Type, Codes),
	relay(T, Outputs0, Outputs)
    ).

relay(error,  Codes) :-
    set_prolog_flag(message_context, []),
    print_error(Codes, []).
relay(output, Codes) :-
    print_output(Codes, []).

print_output(OutCodes, Options) :-
    option(output(Codes), Options),
    !,
    Codes = OutCodes.
print_output(OutCodes, _) :-
    print_message(informational, build(process_output(OutCodes))).

print_error(OutCodes, Options) :-
    option(error(Codes), Options),
    !,
    Codes = OutCodes.
print_error(OutCodes, _) :-
    phrase(classify_message(Level), OutCodes, _),
    print_message(Level, build(process_output(OutCodes))).

classify_message(error) -->
    string(_), "fatal:",
    !.
classify_message(error) -->
    string(_), "error:",
    !.
classify_message(warning) -->
    string(_), "warning:",
    !.
classify_message(informational) -->
    [].


:- multifile user:file_search_path/2.
user:file_search_path(pack_build_path, Dir) :-
    nb_current('$build_tool_env', Env),
    memberchk('PATH'=Path, Env),
    current_prolog_flag(path_sep, Sep),
    atomic_list_concat(Dirs, Sep, Path),
    member(Dir, Dirs),
    Dir \== ''.

%!  has_program(+Spec) is semidet.
%!  has_program(+Spec, -Path) is semidet.
%!  has_program(+Spec, -Path, +Env:list) is semidet.
%
%   True when the OS has the program  Spec at the absolute file location
%   Path. Normally called as   e.g.  has_program(path(cmake), CMakeExe).
%   The second allows passing in an  environment as Name=Value pairs. If
%   this contains a value for ``PATH``,  this   is  used rather than the
%   current path variable.

has_program(Prog) :-
    has_program(Prog, _).
has_program(Program, Path) :-
    has_program(Program, Path, []).

has_program(path(Program), Path, Env), memberchk('PATH'=_, Env) =>
    setup_call_cleanup(
	b_setval('$build_tool_env', Env),
	has_program(pack_build_path(Program), Path, []),
	nb_delete('$build_tool_env')).
has_program(Name, Path, Env), plain_program_name(Name) =>
    has_program(path(Name), Path, Env).
has_program(Program, Path, _Env) =>
    exe_options(ExeOptions),
    absolute_file_name(Program, Path,
		       [ file_errors(fail)
		       | ExeOptions
		       ]).

plain_program_name(Name) :-
    atom(Name),
    \+ sub_atom(Name, _, _, _, '/').

exe_options(Options) :-
    current_prolog_flag(windows, true),
    !,
    Options = [ extensions(['',exe,com]), access(read) ].
exe_options(Options) :-
    Options = [ access(execute) ].


		 /*******************************
		 *             OS PATHS		*
		 *******************************/

setup_path :-
    current_prolog_flag(windows, true),
    \+ current_prolog_flag(msys2, true),
    !,
    setup_path([make, gcc]).
setup_path.

%!  setup_path(+Programs) is det.
%
%   Deals  with  specific  platforms  to  add  specific  directories  to
%   ``$PATH`` such that we can  find   the  tools.  Currently deals with
%   MinGW on Windows to provide `make` and `gcc`.

setup_path(Programs) :-
    maplist(has_program, Programs).
setup_path(_) :-
    current_prolog_flag(windows, true),
    !,
    (   mingw_extend_path
    ->  true
    ;   print_message(error, build(no_mingw))
    ).
setup_path(_).

%!  mingw_extend_path is semidet.
%
%   Check that gcc.exe is on ``%PATH%``  and if not, try to extend the
%   search path.

mingw_extend_path :-
    absolute_file_name(path('gcc.exe'), _,
		       [ access(exist),
			 file_errors(fail)
		       ]),
    !.
mingw_extend_path :-
    mingw_root(MinGW),
    directory_file_path(MinGW, bin, MinGWBinDir),
    atom_concat(MinGW, '/msys/*/bin', Pattern),
    expand_file_name(Pattern, MsysDirs),
    last(MsysDirs, MSysBinDir),
    prolog_to_os_filename(MinGWBinDir, WinDirMinGW),
    prolog_to_os_filename(MSysBinDir, WinDirMSYS),
    getenv('PATH', Path0),
    atomic_list_concat([WinDirMSYS, WinDirMinGW, Path0], ';', Path),
    setenv('PATH', Path),
    print_message(informational,
		  build(mingw_extend_path(WinDirMSYS, WinDirMinGW))).

mingw_root(MinGwRoot) :-
    current_prolog_flag(executable, Exe),
    sub_atom(Exe, 1, _, _, :),
    sub_atom(Exe, 0, 1, _, PlDrive),
    Drives = [PlDrive,c,d],
    member(Drive, Drives),
    format(atom(MinGwRoot), '~a:/MinGW', [Drive]),
    exists_directory(MinGwRoot),
    !.

		 /*******************************
		 *            MESSAGES          *
		 *******************************/

:- multifile prolog:message//1.

prolog:message(build(Msg)) -->
    message(Msg).

message(no_mingw) -->
    [ 'Cannot find MinGW and/or MSYS.'-[] ].
message(process_output(Codes)) -->
    process_output(Codes).
message(step_failed(Step)) -->
    [ 'No build plugin could execute build step ~p'-[Step] ].
message(mingw_extend_path(WinDirMSYS, WinDirMinGW)) -->
    [ 'Extended %PATH% with ~p and ~p'-[WinDirMSYS, WinDirMinGW] ].

%!  process_output(+Codes)//
%
%   Emit process output  using  print_message/2.   This  preserves  line
%   breaks.

process_output([]) -->
    !.
process_output(Codes) -->
    { string_codes(String, Codes),
      split_string(String, "\n", "\r", Lines)
    },
    [ at_same_line ],
    process_lines(Lines).

process_lines([H|T]) -->
    [ '~s'-[H] ],
    (   {T==[""]}
    ->  [nl]
    ;   {T==[]}
    ->  [flush]
    ;   [nl], process_lines(T)
    ).