forked from processone/tsung
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.erl
1643 lines (1488 loc) · 46.5 KB
/
builder.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%%----------------------------------------------------------------------
%%% File : builder.erl
%%% Author : Mats Cronqvist <[email protected]>
%%% : Ulf Wiger <[email protected]>
%%% Purpose : Simplify build of OTP applications & boot scripts
%%% Created : 2 Jan 2001 by Mats Cronqvist <etxmacr@avc386>
%%%----------------------------------------------------------------------
%%% @doc OTP release script builder.
%%%
%%% <p>This program compiles .rel, .script, .boot and sys.config files
%%% for erlang applications. It supports incremental and recursive builds,
%%% and is intended to be (much) easier and safer to use than doing it all
%%% manually. This program does not generate beam code from Erlang source
%%% files.</p>
%%%
%%% <p>The program makes some assumptions:</p>
%%% <ul><li>The application is store in a directory whose name is
%%% composed with the name of the application '-' the version
%%% number of the application (i.e. myapp-1.0)</li>
%%% <li>The release and app file used in input are simplified subset
%%% of the final Erlang release and app file. Some differences:
%%% Versions are handled automatically; You do not need to add
%%% the erts version tuple in the rel.src file; the application,
%%% currently being built is mandatory in the list of apps in the
%%% rel.src file; etc.</li>
%%% </ul>
%%%
%%% <p>The program (henceforth called 'builder') can be customized
%%% using a number of options. The options are prioritized in
%%% the following order: (1) those given as arguments to the
%%% <code>builder:go/1</code> function, those in the BUILD_OPTIONS
%%% file, and (3) the hard-coded defaults.</p>
%%%
%%% <p>Valid options are</p>
%%% <dl>
%%% <dt>{app_dir, dirname()}</dt>
%%% <dd>The application directory of the application being built.
%%% The default value is Current Working Directory.</dd>
%%%
%%% <dt>{build_options, filename()}</dt>
%%% <dd>A filename pointing to a BUILD_OPTIONS file. This is a file
%%% containing erlang expressions, each terminated by "." -- just
%%% like a file processed using file:eval/1. The last expression
%%% in the file should result in a list of
%%% <code>{Key,Value}</code> options.
%%% If this option is not given, builder will look in [AppDir] and
%%% <code>[AppDir]/src</code> for a file called BUILD_OPTIONS.<br/>
%%% Pre-bound variables are:
%%% <ul>
%%% <li><code>ScriptName : filename()</code>,
%%% the name of the script file.</li>
%%% </ul></dd>
%%% <dt>{report, Level : atom()}</dt>
%%% <dd>Specifies the reporting level. The following levels are recognized:
%%% none, progress, verbose, debug.</dd>
%%%
%%% <dt>{out_dir, dirname()}</dt>
%%% <dd>Specifies where [AppName].script, [AppName].boot, and sys.config
%%% should be written. Default is <code>[AppDir]/priv</code>.</dd>
%%%
%%% <dt>{sys_config, filename()}</dt>
%%% <dd>Specifies the location of the sys.config file. Default is
%%% <code>[OutDir]/sys.config</code>.</dd>
%%%
%%% <dt>{rel_file, filename()}</dt>
%%% <dd>Specifies which .rel file should be used as input for the
%%% build process. Default is
%%% <code>[AppDir]/src/[AppName].rel.src</code>.</dd>
%%%
%%% <dt>{rel_name, string()}</dt>
%%% <dd>This option can be used if the release should be called something
%%% other than <code>[AppName]</code> or whatever is in the
%%% <code>.rel</code> file.</dd>
%%%
%%% <dt>{app_vsn, string()}</dt>
%%% <dd>This option can be used to assign a version to the current
%%% application. If the application directory has a version suffix,
%%% the version suffix will override this option. If the directory
%%% has no suffix, the default vsn will be "BLDR", unless 'app_vsn'
%%% has been specified.</dd>
%%%
%%% <dt>{apps, [App : AppName | {AppName,Vsn} | {AppName,Vsn,EbinDir}]}</dt>
%%% <dd>This is a way to identify which applications should be included
%%% in the build. The way builder determines which applications should
%%% be included is this:<ul>
%%% <li>If there is a <code>.rel.src</code> file, the applications
%%% listed in this file are included first, in the order in which
%%% they are listed.</li>
%%% <li>After this, all applications listed in the 'applications'
%%% attribute of the <code>.app.src</code> file are added (if not
%%% already listed), also in the order in which they are listed.</li>
%%% <li>Then, all remaining applications in the 'apps' list are added
%%% in order.</li>
%%% <li>Finally, any included applications listed in the
%%% <code>.rel.src</code> file, not already listed, are added.
%%% (note that applications listed in 'included_applications' of
%%% the <code>.app.src</code> file are not included here. The
%%% <code>.rel</code> file can be used to override this definition,
%%% so it would be an error to include it at this point.)</li>
%%% </ul>
%%% </dd>
%%%
%%% <dt>{path, [PathExpr]}</dt>
%%% <dd>Specifies the search path when locating applications. Default is
%%% code:get_path(). PathExpr can contain wildcards, e.g.
%%% <code>"/OTP/lib/kernel*/ebin"</code> (basically anything that
%%% <code>regexp:sh_to_awk/1</code> understands.)</dd>
%%%
%%% <dt>{skip, [ModuleName : atom()]}</dt>
%%% <dd>Lists modules that should not be included in the generated .app
%%% file for the current application. If not specified, builder will
%%% locate all modules under <code>[AppDir]/src</code>, extract
%%% their module names, and include these module names in the
%%% <code>'modules'</code> list of the <code>.app</code> file.</dd>
%%%
%%% <dt>{make_app, true | false | auto}</dt>
%%% <dd>If true, builder will generate an .app file from an .app.src
%%% file; if false, it will try to use an existing .app file; if
%%% auto, it will build an .app file if no .app file exists
%%% Default is 'auto'.</dd>
%%%
%%% <dt>{make_rel, true | false}</dt>
%%% <dd>If true, builder will generate a .rel file from a .rel.src file;
%%% if false, it will assume that there is a working .rel file.
%%% Default: false if the rel_file option has been specified; true
%%% otherwise.</dd>
%%%
%%% <dt>{make_boot, true | false}</dt>
%%% <dd>If true, builder will run <code>systools:make_script()</code>
%%% to generate .script and .boot files in [OutDir]. If false, it
%%% will assume that there is a working .boot file. Default is true.</dd>
%%% </dl>
%%%
%%% <dt>{systools, Options : [Opt]}</dt>
%%% <dd>If specified, <code>Options</code> will be passed to the
%%% <code>systools:make_script()</code> command for building the
%%% <code>.boot</code> script. Note that the <code>'path'</code> option
%%% is generated by builder. It cannot be overridden.
%%% See <code>erl -man systools</code> for available options.</dd>
%%%
%%% <dt>{sh_script, auto | none}</dt>
%%% <dd>If <code>'auto'</code>, builder will generate a small sh script
%%% that makes it easier to start the system; If <code>'none'</code>,
%%% no script will be generated. Default is <code>'none'</code> on
%%% non-UNIX systems and <code>'auto'</code> on UNIX systems.</dd>
%%%
%%% <dt>{erl_opts, Opts : string()}</dt>
%%% <dd>If specified, and if a sh_script is generated (see above),
%%% <code>Opts</code> will be appended to the <code>erl</code>
%%% command line. The builder will automatically put in options to
%%% identify the boot script, sys.config, and possible boot variables.</dd>
%%%
%%% <dt>{config, Config : {file, filename()} | {M,F,A} | Data}</dt>
%%% <dd>If present, this option should either point to a file that
%%% contains a subset of data for a sys.config file (same format as
%%% sys.config), or give a <code>{M,F,A}</code> tuple, where
%%% <code>apply(M,F,A)</code> results in a list,
%%% <code>[{AppName, [{Key, Value}]}]</code>, or finally just specify
%%% the data in place. The builder will look for similar <code>config</code>
%%% directives in any BUILD_OPTIONS files of other applications that
%%% are part of the build, and all inputs will be merged
%%% into a common <code>sys.config</code>.</dd>
%%%
%%% <dt>{{config,OtherApp}, Config}</dt>
%%% <dd>This is a way to specify environment variables for another
%%% application in the build options. <code>Config</code> in this case
%%% is the same as <code>Config</code> above. The difference between
%%% this option and specifying environment variables for the other
%%% application using the above option, is that with a simple
%%% <code>{config, ...}</code> directive, builder will also check
%%% for a similar directive in the other application, and all
%%% different inputs will be merged. Using a <code>{{config,App},...}</code>
%%% option, builder will not look into that application further.</dd>
%%% @end
%%% =====================================================================
-module(builder).
-author('[email protected]').
-author('[email protected]').
-export([go/0, go/1, find_app/2]).
-export([early_debug_on/0]).
-compile(export_all).
-include_lib("kernel/include/file.hrl").
-import(dict, [fetch/2]).
-define(report(Level, Format, Args),
case do_report(Level) of
true ->
io:format("[~p:~p] " ++ Format, [?MODULE,?LINE|Args]);
false ->
ok
end).
-define(f(D, Expr), fun(D) -> Expr end).
-define(herewith(D), fun(D) ->
?report(debug, "herewith~n", []),
D
end).
early_debug_on() ->
put(builder_debug, true).
go() ->
go([]).
go(Options) ->
%% We use a dictionary for the options. The options are prioritized in
%% the following order: (1) those given as arguments to the go/1 function,
%% those in the BUILD_OPTIONS file, and (3) the hard-coded defaults.
%% The options stored last in the dictionary take precedence, but since
%% we want to allow for the Options list to guide us in finding the
%% BUILD_OPTIONS file (under certain circumstances), we store the defaults
%% and Options list in the dictionary, then locate and read the file, then
%% store the Options list again.
Dict0 = mk_dict(default_options() ++ Options),
Dict = with(Dict0,
[fun(D) -> read_options_file(D) end,
?herewith(D), % to help debugging
fun(D) -> store_options(Options, D) end,
?herewith(D),
fun(D) -> post_process_options(D) end,
?herewith(D),
fun(D) ->
{Path, [App, Vsn]} = get_app(D),
store_options([{app_name, list_to_atom(App)},
{app_vsn, Vsn}], D)
end,
?herewith(D),
fun(D) ->
[Descr, Id, Reg, Apps, Env, Mod, Phases] =
read_app_file(D),
Vsn = fetch(app_vsn, D),
store_options([{app, [{vsn,Vsn}, Descr, Id, Reg,
Apps, Env, Mod, Phases]}], D)
end,
?herewith(D),
fun(D) -> case dict:find(rel_name, D) of
{ok,_} -> D;
error ->
RelName = atom_to_list(
fetch(app_name, D)),
dict:store(rel_name, RelName, D)
end
end,
?herewith(D),
fun(D) ->
RelFname = get_rel_filename(D),
case file:consult(RelFname) of
{ok, [{release,{_Name,_RelVsn},
_RelApps}= Rel]} ->
?report(debug,"rel_src = ~p~n",[Rel]),
dict:store(rel_src,Rel, D);
_ ->
D
end
end,
?herewith(D),
fun(D) -> AppInfo = find_apps(D),
?report(debug, "find_apps(D) -> ~p~n", [AppInfo]),
dict:store(app_info, AppInfo, D)
end,
?herewith(D),
fun(D) ->
BootVars = boot_vars(D),
dict:store(boot_vars, BootVars, D)
end]),
case lists:member({ok,true}, [dict:find(make_boot,Dict),
dict:find(make_rel,Dict),
dict:find(make_config, Dict)]) of
true ->
verify_dir(fetch(out_dir,Dict));
false ->
ok
end,
Dict1 = make_rel(Dict),
make_app(Dict1),
Res = make_boot(Dict1),
make_config(Dict1),
make_sh_script(Dict1),
cleanup(Dict1),
Res.
find_app(App, Path) ->
{Found,_} = expand_path(Path, [App], [], []),
Found.
post_process_options(Dict) ->
D = with(Dict,
[fun(D) -> case dict:find(out_dir, D) of
{ok,_} -> D;
error -> dict:store(out_dir, out_dir(D), D)
end
end,
fun(D) -> case dict:find(rel_file, D) of
{ok,_} -> dict:store(make_rel, false);
error -> dict:store(make_rel, true, D)
end
end,
fun(D) -> case dict:find(config, D) of
{ok,_} -> dict:store(make_config, true, D);
_ -> D
end
end,
fun(D) -> case dict:find(make_boot, D) of
{ok, _} -> D;
error -> dict:store(make_boot, true, D)
end
end,
fun(D) -> case dict:find(make_app, D) of
{ok,_} -> D;
error -> dict:store(make_app, auto, D)
end
end,
fun(D) -> case dict:find(sh_script, D) of
{ok, _} -> D;
error ->
case os:type() of
{unix,_} ->
dict:store(sh_script,auto,D);
_ ->
dict:store(sh_script,none,D)
end
end
end,
fun(D) -> case dict:find(systools, D) of
{ok, _} -> D;
error -> dict:store(systools, [], D)
end
end]),
?report(debug, "Options = ~p~n", [dict:to_list(D)]),
D.
with(Dict, Actions) ->
lists:foldl(fun(F,D) ->
F(D)
end, Dict, Actions).
cleanup(Dict) ->
pop_report_level().
default_options() ->
io:format("default app_dir is ~p~n",[cwd()]),
[{app_dir, cwd()}, {skip, []},
{path, code:get_path()}].
read_options_file(Dict) ->
case dict:find(build_options, Dict) of
{ok, BuildOptsF} ->
case script(BuildOptsF) of
{error, empty_script} ->
%% We accept this
Dict;
{ok, Terms} ->
?report(debug, "Stored terms (~s) =~n ~p~n",
[BuildOptsF, Terms]),
store_options(Terms, Dict);
{error, Reason} ->
exit({bad_options_file, {BuildOptsF, Reason}})
end;
error ->
Path =
case dict:find(app_dir, Dict) of
{ok, AppDir} ->
[AppDir, filename:join(AppDir, "src")];
error ->
[".", "src"]
end,
case path_script(Path, "BUILD_OPTIONS") of
{ok, Terms, Fullname} ->
Dict1 = store_options(Terms, Dict),
?report(debug, "Stored terms (~s) =~n ~p~n",
[Fullname, Terms]),
Dict1;
{error, enoent} ->
Dict;
Error ->
exit({build_options, Error})
end
end.
mk_dict(Options) ->
%% pust a unique ref onto the dictionary. This will allow us to
%% redefine e.g. the report_level (for the same instance of
%% the dictionary, and stack the same (for new instances of the
%% dictionary -- recursive build.)
store_options([{'#ref#', make_ref()}|Options], dict:new()).
store_options(Options, Dict) ->
?report(debug, "store_options(~p)~n", [Options]),
lists:foldl(
fun({report, Level}, D) ->
push_report_level(Level, D),
dict:store(report, Level, D);
({Key,Value}, D) ->
dict:store(Key,Value,D)
end, Dict, Options).
make_rel(Dict) ->
case dict:find(make_rel, Dict) of
{ok,true} ->
?report(debug, "will make rel~n", []),
App = atom_to_list(fetch(app_name, Dict)),
Vsn = fetch_key(vsn, fetch(app, Dict)),
Apps = fetch(app_info, Dict),
AppInfo = [{A,V} || {A,V,F} <- Apps],
?report(debug,"AppInfo = ~p~n", [AppInfo]),
{RelName, Rel} =
case dict:find(rel_src, Dict) of
%% mremond: Added this case clause:
%% Without it you get an error if you define
%% the erts version in your release file subset.
%% The ERTS version is anyway replace by the
%% system ERTS
{ok, {release,{Name,RelVsn}, {erts, ErtsVsn}, RelApps}} ->
?report(debug,"found rel_src: RelApps=~p~n",
[RelApps]),
{Name,
{release, {Name,RelVsn}, {erts, get_erts_vsn()},
AppInfo}};
{ok, {release,{Name,RelVsn},RelApps}} ->
%% here we should check that Apps is a subset of
%% RelApps; if so, use RelApps; otherwise exit
?report(debug,"found rel_src: RelApps=~p~n",
[RelApps]),
{Name,
{release, {Name,RelVsn}, {erts, get_erts_vsn()},
AppInfo}};
error ->
{App,
{release, {App, Vsn}, {erts, get_erts_vsn()},
AppInfo}}
end,
RelFileTarget =
filename:join(fetch(out_dir,Dict), RelName ++ ".rel"),
out(RelFileTarget, Rel),
store_options([{rel_name, RelName},
{rel_file, RelFileTarget}], Dict);
_ ->
?report(debug, "will NOT make rel~n", []),
Dict
end.
make_config(Dict) ->
AppInfo = fetch(app_info, Dict),
AppName = fetch(app_name, Dict),
ForeignData = lists:foldl(
fun({A,V,Ebin}, Acc) when A =/= AppName ->
Acc ++ try_get_config(A,Ebin,Dict);
(_, Acc) ->
Acc
end, [], AppInfo),
Data = case dict:find(config, Dict) of
{ok, Type} ->
get_config_data(Type);
error ->
[]
end,
merge_config(Data ++ ForeignData, Dict).
try_get_config(AppName, Ebin, Dict) ->
case dict:find({config, AppName}, Dict) of
{ok, Type} ->
get_config_data(Type);
error ->
BuildOpts = filename:join(
filename:join(filename:dirname(Ebin), "src"),
"BUILD_OPTIONS"),
case script(BuildOpts) of
{error, enoent} ->
[];
{ok, Result} ->
?report(debug, "script(~p) ->~n ~p~n",
[BuildOpts, Result]),
case lists:keysearch(config, 1, Result) of
{value, {_, Type}} ->
get_config_data(Type);
false ->
[]
end
end
end.
get_config_data({file,F}) ->
?report(debug, "get_config_data({file, ~p})~n", [F]),
case file:consult(F) of
{ok, [Terms]} when list(Terms) ->
Terms;
{error, Reason} ->
exit({config, {F, Reason}})
end;
get_config_data({M,F,A}) ->
?report(debug, "get_config_data(~p)~n", [{M,F,A}]),
apply(M,F,A);
get_config_data(Data) when list(Data) ->
Data.
merge_config([], Dict) ->
ok;
merge_config(Data, Dict) ->
ConfigF = sys_config(Dict),
case file:consult(ConfigF) of
{error, enoent} ->
out(ConfigF, Data);
{ok, [Terms]} ->
?report(debug, "merging terms (~p,~p), F = ~p~n",
[Data,Terms, ConfigF]),
NewData = merge_terms(Data, Terms),
out(ConfigF, NewData)
end.
merge_terms([{App,Vars}|Data], Old) ->
case lists:keysearch(App, 1, Old) of
false ->
merge_terms(Data, Old ++ [{App,Vars}]);
{value, {_, OldVars}} ->
?report(debug, "merging vars (~p,~p) for ~p~n",
[Vars,OldVars, App]),
NewVars = merge_vars(Vars, OldVars, App),
merge_terms(Data, lists:keyreplace(App,1,Old,{App,NewVars}))
end;
merge_terms([], Data) ->
Data.
merge_vars([{Key,Vals}|Data], Old, App) ->
case lists:keysearch(Key, 1, Old) of
{value, {_, OldVals}} when OldVals =/= Vals ->
exit({config_conflict, {App, Key}});
{value, {_, OldVals}} when OldVals == Vals ->
merge_vars(Data, Old, App);
false ->
merge_vars(Data, Old ++ [{Key,Vals}], App)
end;
merge_vars([], Data, _App) ->
Data.
fetch_key(Key, L) ->
{value, {_, Value}} = lists:keysearch(Key, 1, L),
Value.
make_app(Dict) ->
case dict:find(make_app, Dict) of
{ok,true} ->
do_make_app(Dict);
{ok,auto} ->
AppName = fetch(app_name, Dict),
AppF = filename:join(ebin_dir(Dict),
atom_to_list(AppName) ++ ".app"),
case file:read_file_info(AppF) of
{ok, _} ->
ok;
{error, enoent} ->
do_make_app(AppF, AppName, Dict)
end;
_ ->
ok
end.
do_make_app(Dict) ->
AppName = fetch(app_name, Dict),
AppF = filename:join(ebin_dir(Dict), atom_to_list(AppName) ++ ".app"),
do_make_app(AppF, AppName, Dict).
do_make_app(AppF, AppName, Dict) ->
[Vsn, Descr, Id, Reg, Apps, Env, Mod, Phases] = fetch(app, Dict),
Modules = modules(Dict),
Remove = case {Mod, Phases} of
{{_,[]},{_,undefined}} -> [Mod, Phases];
{{_,{_,_}},{_,undefined}} -> [Phases];
{{_,[]}, {_,_}} -> [Mod];
_ -> []
end,
Options = [Vsn, Descr, Id, Modules,
Reg, Apps, Env, Mod, Phases] -- Remove,
out(AppF, {application, AppName, Options}).
make_boot(Dict) ->
case dict:find(make_boot, Dict) of
{ok,true} ->
ensure_rel_file(Dict),
App = fetch(app_name, Dict),
CWD = cwd(),
ok = file:set_cwd(fetch(out_dir,Dict)),
SystoolsOpts0 = merge_opts([{path, systools_path(Dict)}],
fetch(systools, Dict)),
SystoolsOpts = maybe_local(SystoolsOpts0, Dict),
?report(debug, "SystoolsOpts = ~p~n", [SystoolsOpts]),
RelName = fetch(rel_name, Dict),
Res = systools:make_script(RelName, SystoolsOpts),
?report(progress, "systools:make_script() -> ~p~n", [Res]),
make_load_script(RelName),
ok = file:set_cwd(CWD),
case Res of
error ->
exit(error_in_make_script);
ok ->
ok
end;
_ ->
ok
end.
maybe_local(Opts, Dict) ->
case lists:keymember(variables, 1, Opts) of
true ->
Opts;
false ->
[local|Opts -- [local]]
end.
make_load_script(RelName) ->
{ok, Bin} = file:read_file(RelName ++ ".boot"),
{script,Id,Cmds} = binary_to_term(Bin),
Keep =
lists:filter(
fun({apply,{application,start_boot,[kernel,Type]}}) -> true;
({apply,{application,start_boot,[stdlib,Type]}}) -> true;
({apply,{application,start_boot,[sasl,Type]}}) -> true;
({apply,{application,start_boot,[_,Type]}}) -> false;
(_) ->
true
end, Cmds),
NewScript = {script,Id,Keep},
file:write_file(RelName ++ "_load.boot", term_to_binary(NewScript)),
out(RelName ++ "_load.script", NewScript).
boot_vars(Dict) ->
case dict:find(systools, Dict) of
{ok, Opts} when Opts =/= [] ->
?report(debug, "systools opts = ~p~n", [Opts]),
case lists:keysearch(variables, 1, Opts) of
{value, {_, Vars}} ->
Vars;
false ->
[]
end;
_ ->
?report(debug,"will make boot_vars~n", []),
{ok,[[Root]]} = init:get_argument(root),
Apps = dict:fetch(app_info, Dict),
prefixes(Apps, [{"ROOT",Root}])
end.
prefixes([{A,_,D}|Apps], Prefixes) ->
case [P || {_,P} <- Prefixes,
lists:prefix(P, D)] of
[] ->
prefixes(Apps, guess_root(D, Prefixes));
[_|_] ->
prefixes(Apps, Prefixes)
end;
prefixes([], Prefixes) ->
Prefixes.
guess_root(D, Pfxs) ->
case lists:reverse(filename:split(D)) of
["ebin",App,"lib",Dir|T] ->
guess(to_upper(Dir), 0,
filename:join(lists:reverse([Dir|T])), Pfxs);
["ebin",App,Dir|T] ->
guess(to_upper(Dir), 0,
filename:join(lists:reverse([Dir|T])), Pfxs)
end.
guess(Guess,N,RootDir, Pfxs) ->
case lists:keymember(Guess,1,Pfxs) of
false ->
?report(debug, "manufactured boot_var {~p,~p}~n",
[Guess,RootDir]),
[{Guess,RootDir}|Pfxs];
true ->
?report(debug, "duplicate Guess = ~p~n", [Guess]),
guess(increment(Guess,N), N+1, RootDir, Pfxs)
end.
increment(Guess,0) ->
Guess ++ "-1";
increment(Guess,N) when N < 10 ->
[_,$-|T] = lists:reverse(Guess),
lists:reverse(T) ++ [$-|integer_to_list(N+1)].
to_upper([H|T]) when H >= $a, H =< $z ->
[$A+(H-$a)|to_upper(T)];
to_upper([H|T]) ->
[H|T];
to_upper([]) ->
[].
make_sh_script(Dict) ->
case dict:find(sh_script, Dict) of
{ok, auto} ->
OutDir = fetch(out_dir, Dict),
RelName = fetch(rel_name, Dict),
StartF = filename:join(OutDir, RelName ++ ".start"),
LoadF = filename:join(OutDir, RelName ++ ".load"),
do_make_sh_script(StartF,start,Dict),
do_make_sh_script(LoadF,load,Dict);
_ ->
ok
end.
do_make_sh_script(ScriptF, Type, Dict) ->
ok = file:write_file(ScriptF, list_to_binary(
sh_script(ScriptF, Type,Dict))),
{ok,FI} = file:read_file_info(ScriptF),
Mode = FI#file_info.mode bor 8#00100,
ok = file:write_file_info(ScriptF, FI#file_info{mode = Mode}).
sh_script(Fname, Mode,Dict) ->
OutDir = fetch(out_dir, Dict),
AppDir = fetch(app_dir, Dict),
BaseName = filename:basename(Fname),
XOpts = case dict:find(erl_opts, Dict) of
{ok, Opts} ->
Opts;
error ->
[]
end,
OptionalSname =
case re:run(XOpts, "-sname",[{capture,all_but_first,binary},dotall]) of
{match,_,_} -> false;
nomatch -> true
end,
?report(debug, "OptionalSname (~p) = ~p~n", [XOpts, OptionalSname]),
%% mremond: The path it need to be sure the script is predictible
% Path = [" -pa ", filename:join(AppDir, "ebin")],
RelName = fetch(rel_name, Dict),
Boot = case Mode of
start -> [" -boot ", filename:join(OutDir, RelName)];
load -> [" -boot ", filename:join(OutDir, RelName++"_load")]
end,
Sys = case dict:find(make_config, Dict) of
{ok, true} ->
[" -config ", filename:join(OutDir, "sys")];
_ ->
[]
end,
BootVars = [[" -boot_var ", Var, " ", Dir] ||
{Var,Dir} <- dict:fetch(boot_vars, Dict)],
% ["#/bin/sh\n"
% "erl ", Boot, Sys, BootVars, XOpts, "\n"].
["#!/bin/bash\n",
"ERL=\"`which erl`\"\n",
case OptionalSname of
true -> "SNAME=\"\"\n";
false -> ""
end,
"\n"
"while [ \$# -gt 0 ]\n"
" do\n"
" case \$1 in\n"
" -erl)\n"
" ERL=\"\$2\"\n"
" shift\n"
" ;;\n",
case OptionalSname of
true ->
(" -sname)\n"
" SNAME=\"\-sname $2\"\n"
" shift\n"
" ;;\n");
false ->
""
end,
" *)\n"
" echo \"Faulty arguments: \$*\"\n"
" echo \"usage: ", BaseName, (
[" [-erl <ErlLocation>]",
case OptionalSname of
true -> " [-sname <Sname>]";
false -> ""
end, "\"\n"]),
" exit 1\n"
" ;;\n"
" esac\n"
" shift\n"
" done\n"
"\n",
case OptionalSname of
true ->
["\$ERL \$SNAME", Boot, Sys, BootVars, opt_space(XOpts), "\n"];
false ->
["\$ERL", Boot, Sys, BootVars, opt_space(XOpts), "\n"]
end
].
opt_space([]) ->
[];
opt_space([_|_] = L) ->
[$\s|L].
ensure_rel_file(Dict) ->
OutDir = fetch(out_dir, Dict),
case dict:find(rel_file, Dict) of
{ok, F} ->
case filename:dirname(F) of
D when D == OutDir ->
ok;
_ ->
%% This doesn't necessarily mean that it's not there
RelName = fetch(rel_name, Dict),
{ok, [{release, {N,Vsn}, Erts, Apps}]} =
file:consult(F),
RelF = filename:join(OutDir,
fetch(rel_name,Dict) ++ ".rel"),
out(RelF, {release, {RelName,Vsn}, Erts, Apps})
end;
error ->
exit(no_rel_file)
end.
systools_path(Dict) ->
AppInfo = fetch(app_info, Dict),
[D || {_A,_V,D} <- AppInfo].
merge_opts(Opts, [{path,P}|Opts2]) ->
exit({not_allowed, {systools, {path,P}}});
merge_opts(Opts, [Opt|Opts2]) ->
[Opt|merge_opts(Opts, Opts2)];
merge_opts(Opts, []) ->
Opts.
cwd() ->
{ok, CWD} = file:get_cwd(),
CWD.
out_dir(Dict) ->
case dict:find(out_dir, Dict) of
{ok, OutDir} ->
OutDir;
error ->
filename:join(fetch(app_dir,Dict), "priv")
end.
ebin_dir(Dict) ->
AppDir = fetch(app_dir, Dict),
filename:join(AppDir, "ebin").
sys_config(Dict) ->
case dict:find(sys_config, Dict) of
{ok, Filename} ->
Filename;
error ->
filename:join(fetch(out_dir,Dict), "sys.config")
end.
get_app(Dict) ->
AppDir = fetch(app_dir, Dict),
%% mremond: The program was crashing when the directory where not
%% containing the application version
%% Now we assume that version number is "BLDR" by default.
case string:tokens(hd(lists:reverse(string:tokens(AppDir, "/"))), "-") of
[App, Vsn] -> {AppDir, [App, Vsn]};
[App] ->
case dict:find(app_vsn, Dict) of
{ok, Vsn} ->
{AppDir, [App, Vsn]};
error ->
{AppDir, [App, "BLDR"]}
end
end.
get_app_filename(App, Dict) ->
AppDir = fetch(app_dir, Dict),
filename:join([AppDir, "src", App++".app.src"]).
get_rel_filename(Dict) ->
App = atom_to_list(dict:fetch(app_name, Dict)),
AppDir = fetch(app_dir, Dict),
filename:join([AppDir, "src", App++".rel.src"]).
modules(Dict) ->
Ebin = ebin_dir(Dict),
Ext = code:objfile_extension(),
?report(debug, "looking for modules (~p) in ~p~n", [Ext,Ebin]),
L = recursive_list_dir(Ebin),
?report(debug, "L = ~p~n", [L]),
Skip = fetch(skip, Dict),
?report(debug, "Skip = ~p~n", [Skip]),
Modules = lists:foldr(
fun(F, Acc) ->
case make_mod(F) of
{ok, M} ->
[M|Acc];
error ->
Acc
end
end, [], [F || F <- L,
check_f(F, Ext)]),
{modules, Modules -- Skip}.
recursive_list_dir(Dir) ->
?report(debug, "recursive_list_dir(~p)~n", [Dir]),
{ok, Fs} = file:list_dir(Dir),
lists:concat([f_expand(F,Dir) || F <- Fs]).
f_expand(Name,Dir) ->
Fname = filename:join(Dir,Name),
case file:read_file_info(Fname) of
{ok, #file_info{type=regular}} ->
[Fname];
{ok, #file_info{type=directory}} ->
?report(debug, "~p is a directory under ~p~n", [Fname, Dir]),
{ok, Fs} = file:list_dir(Fname),
lists:concat([f_expand(F,Fname) || F <- Fs]);
{ok, Finfo} ->
?report(debug, "~p not a directory or a regular file. Ignoring~n",
[Fname]),
[];
{error, Reason} ->
?report(error, "*** read_file_info(~p) -> {error, ~p}~n",
[Fname, Reason]),
[]
end.
make_mod(F) ->
case beam_lib:version(F) of
{ok, {Module, Vsn}} ->
{ok, Module};
_ ->
error
end.
% {ok,Fd} = file:open(F, [read]),
% parse_for_mod(Fd, F).
% {ok,Bin} = file:read_file(F),
% Text = binary_to_list(Bin),
% {match,Start,Len} =
% regexp:first_match(Text,
% "^[ ]*-[ ]*module[ ]*[(][ ]*.*[ ]*[)][ ]*\."),
% Name = case string:substr(Text, Start+8,Len-10) of
% "'" ++ Quoted ->
% "'" ++ Rest = lists:reverse(Quoted),
% list_to_atom(lists:reverse(Rest));
% Str ->
% list_to_atom(Str)
% end.
parse_for_mod(Fd, F) ->
parse_for_mod(Fd, io:parse_erl_exprs(Fd,''), F).
parse_for_mod(Fd, {ok,[{op,_,'-',{call,_,{atom,_,module},[Mod]}}],_}, F) ->
{ok,parse_mod_expr(Mod)};
% parse_for_mod(Fd, {ok,[{op,_,'-',
% {call,_,{atom,_,module},[{atom,_,Mod}]}}],_}, F) ->
% {ok,Mod};
parse_for_mod(Fd, {ok,_,_}, F) ->
parse_for_mod(Fd, io:parse_erl_exprs(Fd,''), F);
parse_for_mod(Fd, {error,_,_}=Error, F) ->
io:format("*** Error parsing ~s: ~p~n", [F, Error]),
error;
parse_for_mod(Fd, {eof,_}, F) ->
io:format("*** No module attribute found in ~s~n", [F]),
error.
parse_mod_expr(Expr) ->
list_to_atom(parse_mod_expr1(Expr)).
parse_mod_expr1({atom,_,A}) ->
atom_to_list(A);
parse_mod_expr1({record_field,_,R,{atom,_,A}}) ->
parse_mod_expr1(R) ++ "." ++ atom_to_list(A).
check_f(F, Ext) ->
case re:run(F, ".*"++Ext++"\$",[{capture,all_but_first,binary},dotall]) of
{match, _, _} -> true;
_ -> false
end.