emqx_machine_boot_runtime_deps.erl 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_machine_boot_runtime_deps).
  17. -export([inject/2]).
  18. -type app_name() :: atom().
  19. -type app_deps() :: {app_name(), [app_name()]}.
  20. -type app_selector() :: app_name() | fun((app_name()) -> boolean()).
  21. -type runtime_dep() :: {_WhatDepends :: app_name(), _OnWhat :: app_selector()}.
  22. -spec inject([app_deps()], [runtime_dep()]) -> [app_deps()].
  23. inject(AppDepList, DepSpecs) ->
  24. AppDep0 = maps:from_list(AppDepList),
  25. AppDep1 = lists:foldl(
  26. fun(DepSpec, AppDepAcc) ->
  27. inject_one_dep(AppDepAcc, DepSpec)
  28. end,
  29. AppDep0,
  30. DepSpecs
  31. ),
  32. maps:to_list(AppDep1).
  33. %%--------------------------------------------------------------------
  34. %% Internal functions
  35. %%--------------------------------------------------------------------
  36. inject_one_dep(AppDep, {WhatDepends, OnWhatSelector}) ->
  37. OnWhat = select_apps(OnWhatSelector, maps:keys(AppDep)),
  38. case AppDep of
  39. #{WhatDepends := Deps} when is_list(Deps) ->
  40. AppDep#{WhatDepends => lists:usort(Deps ++ OnWhat)};
  41. _ ->
  42. AppDep
  43. end.
  44. select_apps(AppName, AppNames) when is_atom(AppName) ->
  45. lists:filter(fun(App) -> App =:= AppName end, AppNames);
  46. select_apps(AppSelector, AppNames) when is_function(AppSelector, 1) ->
  47. lists:filter(AppSelector, AppNames).