summaryrefslogtreecommitdiff
path: root/src/rebar_state.erl
blob: d0b28de8eeed67b7991e45df640b3c8e72cf5d0e (plain)
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
-module(rebar_state).

-export([new/0, new/1, new/2, new/3,

         get/2, get/3, set/3,

         format_error/1,

         has_all_artifacts/1,

         code_paths/2, code_paths/3, update_code_paths/3,

         opts/1, opts/2,
         default/1, default/2,

         escript_path/1, escript_path/2,

         lock/1, lock/2,

         current_profiles/1, current_profiles/2,

         command_args/1, command_args/2,
         command_parsed_args/1, command_parsed_args/2,

         add_to_profile/3, apply_profiles/2,

         dir/1, dir/2,
         create_logic_providers/2,

         project_apps/1, project_apps/2,
         deps_to_build/1, deps_to_build/2,
         all_plugin_deps/1, all_plugin_deps/2, update_all_plugin_deps/2,
         all_deps/1, all_deps/2, update_all_deps/2,
         namespace/1, namespace/2,

         deps_names/1,

         overrides/1, overrides/2,
         apply_overrides/2,

         packages/1, packages/2,
         registry/1, registry/2,

         resources/1, resources/2, add_resource/2,
         providers/1, providers/2, add_provider/2]).

-include("rebar.hrl").
-include_lib("providers/include/providers.hrl").

-record(state_t, {dir                               :: file:name(),
                  opts                = dict:new()  :: rebar_dict(),
                  code_paths          = dict:new()  :: rebar_dict(),
                  default             = dict:new()  :: rebar_dict(),
                  escript_path                      :: undefined | file:filename_all(),

                  lock                = [],
                  current_profiles    = [default]     :: [atom()],
                  namespace           = default       :: atom(),

                  command_args        = [],
                  command_parsed_args = {[], []},

                  project_apps        = []          :: [rebar_app_info:t()],
                  deps_to_build       = []          :: [rebar_app_info:t()],
                  all_plugin_deps     = []          :: [rebar_app_info:t()],
                  all_deps            = []          :: [rebar_app_info:t()],

                  packages            = undefined   :: {rebar_dict(), rebar_digraph()} | undefined,
                  registry            = undefined   :: {ok, ets:tid()} | error | undefined,
                  overrides           = [],
                  resources           = [],
                  providers           = []}).

-export_type([t/0]).

-type t() :: #state_t{}.

-spec new() -> t().
new() ->
    BaseState = base_state(),
    BaseState#state_t{dir = rebar_dir:get_cwd()}.

-spec new(list()) -> t().
new(Config) when is_list(Config) ->
    BaseState = base_state(),
    Deps = proplists:get_value(deps, Config, []),
    Plugins = proplists:get_value(plugins, Config, []),
    Terms = [{{deps, default}, Deps}, {{plugins, default}, Plugins} | Config],
    true = rebar_config:verify_config_format(Terms),
    Opts = dict:from_list(Terms),
    BaseState#state_t { dir = rebar_dir:get_cwd(),
                        default = Opts,
                        opts = Opts }.

-spec new(t() | atom(), list()) -> t().
new(Profile, Config) when is_atom(Profile)
                        , is_list(Config) ->
    BaseState = base_state(),
    Deps = proplists:get_value(deps, Config, []),

    Plugins = proplists:get_value(plugins, Config, []),
    Terms = [{{deps, default}, Deps}, {{plugins, default}, Plugins} | Config],
    true = rebar_config:verify_config_format(Terms),
    Opts = dict:from_list(Terms),
    BaseState#state_t { dir = rebar_dir:get_cwd(),
                        current_profiles = [Profile],
                        default = Opts,
                        opts = Opts };
new(ParentState=#state_t{}, Config) ->
    %% Load terms from rebar.config, if it exists
    Dir = rebar_dir:get_cwd(),
    new(ParentState, Config, Dir).

-spec new(t(), list(), file:name()) -> t().
new(ParentState, Config, Dir) ->
    Opts = ParentState#state_t.opts,
    LocalOpts = case rebar_config:consult_lock_file(filename:join(Dir, ?LOCK_FILE)) of
                    [D] ->
                        %% We want the top level deps only from the lock file.
                        %% This ensures deterministic overrides for configs.
                        Deps = [X || X <- D, element(3, X) =:= 0],
                        Plugins = proplists:get_value(plugins, Config, []),
                        Terms = [{{locks, default}, D}, {{deps, default}, Deps}, {{plugins, default}, Plugins} | Config],
                        true = rebar_config:verify_config_format(Terms),
                        dict:from_list(Terms);
                    _ ->
                        D = proplists:get_value(deps, Config, []),
                        Plugins = proplists:get_value(plugins, Config, []),
                        Terms = [{{deps, default}, D}, {{plugins, default}, Plugins} | Config],
                        true = rebar_config:verify_config_format(Terms),
                        dict:from_list(Terms)
                end,

    NewOpts = merge_opts(LocalOpts, Opts),

    ParentState#state_t{dir=Dir
                       ,opts=NewOpts
                       ,default=NewOpts}.

base_state() ->
    case application:get_env(rebar, resources) of
        undefined ->
            Resources = [];
        {ok, Resources} ->
            Resources
    end,
    #state_t{resources=Resources}.

get(State, Key) ->
    {ok, Value} = dict:find(Key, State#state_t.opts),
    Value.

get(State, Key, Default) ->
    case dict:find(Key, State#state_t.opts) of
        {ok, Value} ->
            Value;
        error ->
            Default
    end.

-spec set(t(), any(), any()) -> t().
set(State=#state_t{opts=Opts}, Key, Value) ->
    State#state_t{ opts = dict:store(Key, Value, Opts) }.

default(#state_t{default=Opts}) ->
    Opts.

default(State, Opts) ->
    State#state_t{default=Opts}.

format_error({profile_not_list, Profile, Other}) ->
    io_lib:format("Profile config must be a list but for profile '~p' config given as:~n~p", [Profile, Other]).

-spec has_all_artifacts(rebar_app_info:t()) -> true | providers:error().
has_all_artifacts(State) ->
    Artifacts = rebar_state:get(State, artifacts, []),
    Dir = rebar_dir:base_dir(State),
    all(Dir, Artifacts).

all(_, []) ->
    true;
all(Dir, [File|Artifacts]) ->
    case filelib:is_regular(filename:join(Dir, File)) of
        false ->
            ?DEBUG("Missing artifact ~s", [filename:join(Dir, File)]),
            {false, File};
        true ->
            all(Dir, Artifacts)
    end.

code_paths(#state_t{code_paths=CodePaths}, Key) ->
    case dict:find(Key, CodePaths) of
        {ok, CodePath} ->
            CodePath;
        _ ->
            []
    end.

code_paths(State=#state_t{code_paths=CodePaths}, Key, CodePath) ->
    State#state_t{code_paths=dict:store(Key, CodePath, CodePaths)}.

update_code_paths(State=#state_t{code_paths=CodePaths}, Key, CodePath) ->
    case dict:is_key(Key, CodePaths) of
        true ->
            State#state_t{code_paths=dict:append_list(Key, CodePath, CodePaths)};
        false ->
            State#state_t{code_paths=dict:store(Key, CodePath, CodePaths)}
    end.

opts(#state_t{opts=Opts}) ->
    Opts.

opts(State, Opts) ->
    State#state_t{opts=Opts}.

current_profiles(#state_t{current_profiles=Profiles}) ->
    Profiles.

current_profiles(State, Profiles) ->
    State#state_t{current_profiles=Profiles}.

lock(#state_t{lock=Lock}) ->
    Lock.

lock(State=#state_t{}, Apps) when is_list(Apps) ->
    State#state_t{lock=Apps};
lock(State=#state_t{lock=Lock}, App) ->
    State#state_t{lock=[App | Lock]}.

escript_path(#state_t{escript_path=EscriptPath}) ->
    EscriptPath.

escript_path(State, EscriptPath) ->
    State#state_t{escript_path=EscriptPath}.

command_args(#state_t{command_args=CmdArgs}) ->
    CmdArgs.

command_args(State, CmdArgs) ->
    State#state_t{command_args=CmdArgs}.

command_parsed_args(#state_t{command_parsed_args=CmdArgs}) ->
    CmdArgs.

command_parsed_args(State, CmdArgs) ->
    State#state_t{command_parsed_args=CmdArgs}.

apply_overrides(State=#state_t{overrides=Overrides}, AppName) ->
    Name = binary_to_atom(AppName, utf8),

    %% Inefficient. We want the order we get here though.
    State1 = lists:foldl(fun({override, O}, StateAcc) ->
                                 lists:foldl(fun({Key, Value}, StateAcc1) ->
                                                     rebar_state:set(StateAcc1, Key, Value)
                                             end, StateAcc, O);
                            (_, StateAcc) ->
                                 StateAcc
                         end, State, Overrides),

    State2 = lists:foldl(fun({override, N, O}, StateAcc) when N =:= Name ->
                                 lists:foldl(fun({Key, Value}, StateAcc1) ->
                                                     rebar_state:set(StateAcc1, Key, Value)
                                             end, StateAcc, O);
                            (_, StateAcc) ->
                                 StateAcc
                         end, State1, Overrides),

    State3 = lists:foldl(fun({add, N, O}, StateAcc) when N =:= Name ->
                        lists:foldl(fun({Key, Value}, StateAcc1) ->
                                            OldValue = rebar_state:get(StateAcc1, Key, []),
                                            rebar_state:set(StateAcc1, Key, Value++OldValue)
                                    end, StateAcc, O);
                   (_, StateAcc) ->
                        StateAcc
                end, State2, Overrides),

    Opts = opts(State3),
    State3#state_t{default=Opts}.

add_to_profile(State, Profile, KVs) when is_atom(Profile), is_list(KVs) ->
    Profiles = rebar_state:get(State, profiles, []),
    ProfileOpts = dict:from_list(proplists:get_value(Profile, Profiles, [])),
    NewOpts = merge_opts(Profile, dict:from_list(KVs), ProfileOpts),
    NewProfiles = [{Profile, dict:to_list(NewOpts)}|lists:keydelete(Profile, 1, Profiles)],
    rebar_state:set(State, profiles, NewProfiles).

apply_profiles(State, Profile) when not is_list(Profile) ->
    apply_profiles(State, [Profile]);
apply_profiles(State, [default]) ->
    State;
apply_profiles(State=#state_t{default = Defaults, current_profiles=CurrentProfiles}, Profiles) ->
    AppliedProfiles = deduplicate(CurrentProfiles ++ Profiles),
    ConfigProfiles = rebar_state:get(State, profiles, []),

    NewOpts =
        lists:foldl(fun(default, OptsAcc) ->
                            OptsAcc;
                       (Profile, OptsAcc) ->
                            case proplists:get_value(Profile, ConfigProfiles, []) of
                                OptsList when is_list(OptsList) ->
                                    ProfileOpts = dict:from_list(OptsList),
                                    merge_opts(Profile, ProfileOpts, OptsAcc);
                                Other ->
                                    throw(?PRV_ERROR({profile_not_list, Profile, Other}))
                            end
                    end, Defaults, AppliedProfiles),
    State#state_t{current_profiles = AppliedProfiles, opts=NewOpts}.

deduplicate(Profiles) ->
    do_deduplicate(lists:reverse(Profiles), []).

do_deduplicate([], Acc) ->
    Acc;
do_deduplicate([Head | Rest], Acc) ->
    case lists:member(Head, Acc) of
        true -> do_deduplicate(Rest, Acc);
        false -> do_deduplicate(Rest, [Head | Acc])
    end.

merge_opts(Profile, NewOpts, OldOpts) ->
    Opts = merge_opts(NewOpts, OldOpts),

    Opts2 = case dict:find(plugins, NewOpts) of
        {ok, Value} ->
            dict:store({plugins, Profile}, Value, Opts);
        error ->
            Opts
    end,

    case dict:find(deps, NewOpts) of
        {ok, Value2} ->
            dict:store({deps, Profile}, Value2, Opts2);
        error ->
            Opts2
    end.

merge_opts(NewOpts, OldOpts) ->
    dict:merge(fun(deps, NewValue, _OldValue) ->
                       NewValue;
                  ({deps, _}, NewValue, _OldValue) ->
                       NewValue;
                  (plugins, NewValue, _OldValue) ->
                       NewValue;
                  ({plugins, _}, NewValue, _OldValue) ->
                       NewValue;
                  (profiles, NewValue, OldValue) ->
                       dict:to_list(merge_opts(dict:from_list(NewValue), dict:from_list(OldValue)));
                  (_Key, NewValue, OldValue) when is_list(NewValue) ->
                       case io_lib:printable_list(NewValue) of
                           true when NewValue =:= [] ->
                               case io_lib:printable_list(OldValue) of
                                   true ->
                                       NewValue;
                                   false ->
                                       OldValue
                               end;
                           true ->
                               NewValue;
                           false ->
                               rebar_utils:tup_umerge(rebar_utils:tup_sort(NewValue)
                                                     ,rebar_utils:tup_sort(OldValue))
                       end;
                  (_Key, NewValue, _OldValue) ->
                       NewValue
               end, NewOpts, OldOpts).

dir(#state_t{dir=Dir}) ->
    Dir.

dir(State=#state_t{}, Dir) ->
    State#state_t{dir=filename:absname(Dir)}.

deps_names(Deps) when is_list(Deps) ->
    lists:map(fun(Dep) when is_tuple(Dep) ->
                      ec_cnv:to_binary(element(1, Dep));
                 (Dep) when is_atom(Dep) ->
                      ec_cnv:to_binary(Dep)
              end, Deps);
deps_names(State) ->
    Deps = rebar_state:get(State, deps, []),
    deps_names(Deps).

overrides(#state_t{overrides=Overrides}) ->
    Overrides.

overrides(State=#state_t{}, Overrides) ->
    State#state_t{overrides=Overrides}.

project_apps(#state_t{project_apps=Apps}) ->
    Apps.

project_apps(State=#state_t{}, NewApps) when is_list(NewApps) ->
    State#state_t{project_apps=NewApps};
project_apps(State=#state_t{project_apps=Apps}, App) ->
    State#state_t{project_apps=lists:keystore(rebar_app_info:name(App), 2, Apps, App)}.

deps_to_build(#state_t{deps_to_build=Apps}) ->
    Apps.

deps_to_build(State=#state_t{deps_to_build=Apps}, NewApps) when is_list(NewApps) ->
    State#state_t{deps_to_build=Apps++NewApps};
deps_to_build(State=#state_t{deps_to_build=Apps}, App) ->
    State#state_t{deps_to_build=lists:keystore(rebar_app_info:name(App), 2, Apps, App)}.

all_deps(#state_t{all_deps=Apps}) ->
    Apps.

all_deps(State=#state_t{}, NewApps) ->
    State#state_t{all_deps=NewApps}.

all_plugin_deps(#state_t{all_plugin_deps=Apps}) ->
    Apps.

all_plugin_deps(State=#state_t{}, NewApps) ->
    State#state_t{all_plugin_deps=NewApps}.

update_all_plugin_deps(State=#state_t{all_plugin_deps=Apps}, NewApps) ->
    State#state_t{all_plugin_deps=Apps++NewApps}.

update_all_deps(State=#state_t{all_deps=Apps}, NewApps) ->
    State#state_t{all_deps=Apps++NewApps}.

namespace(#state_t{namespace=Namespace}) ->
    Namespace.

namespace(State=#state_t{}, Namespace) ->
    State#state_t{namespace=Namespace}.

packages(State=#state_t{packages=undefined}) ->
    rebar_packages:get_packages(State);
packages(#state_t{packages=Packages}) ->
    Packages.

packages(State, Packages) ->
    State#state_t{packages=Packages}.

registry(State=#state_t{registry=undefined}) ->
    rebar_packages:registry(State);
registry(#state_t{registry=Registry}) ->
    Registry.

registry(State, Registry) ->
    State#state_t{registry=Registry}.

-spec resources(t()) -> rebar_resource:resource().
resources(#state_t{resources=Resources}) ->
    Resources.

-spec resources(t(), [rebar_resource:resource()]) -> t().
resources(State, NewResources) ->
    State#state_t{resources=NewResources}.

-spec add_resource(t(), rebar_resource:resource()) -> t().
add_resource(State=#state_t{resources=Resources}, Resource) ->
    State#state_t{resources=[Resource | Resources]}.

providers(#state_t{providers=Providers}) ->
    Providers.

providers(State, NewProviders) ->
    State#state_t{providers=NewProviders}.

-spec add_provider(t(), providers:t()) -> t().
add_provider(State=#state_t{providers=Providers}, Provider) ->
    State#state_t{providers=[Provider | Providers]}.

create_logic_providers(ProviderModules, State0) ->
    try
        lists:foldl(fun(ProviderMod, StateAcc) ->
                            case providers:new(ProviderMod, StateAcc) of
                                {error, Reason} ->
                                    ?ERROR(Reason++"~n", []),
                                    StateAcc;
                                {ok, StateAcc1} ->
                                    StateAcc1
                            end
                    end, State0, ProviderModules)
    catch
        C:T ->
            ?DEBUG("~p: ~p ~p", [C, T, erlang:get_stacktrace()]),
            throw({error, "Failed creating providers. Run with DEBUG=1 for stacktrace."})
    end.

%% ===================================================================
%% Internal functions
%% ===================================================================