emqx_hocon.erl 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2022 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. %% @doc HOCON schema help module
  17. -module(emqx_hocon).
  18. -export([
  19. format_path/1,
  20. check/2
  21. ]).
  22. %% @doc Format hocon config field path to dot-separated string in iolist format.
  23. -spec format_path([atom() | string() | binary()]) -> iolist().
  24. format_path([]) -> "";
  25. format_path([Name]) -> iol(Name);
  26. format_path([Name | Rest]) -> [iol(Name), "." | format_path(Rest)].
  27. %% @doc Plain check the input config.
  28. %% The input can either be `richmap' or plain `map'.
  29. %% Always return plain map with atom keys.
  30. -spec check(module(), hocon:config() | iodata()) ->
  31. {ok, hocon:config()} | {error, any()}.
  32. check(SchemaModule, Conf) when is_map(Conf) ->
  33. %% TODO: remove required
  34. %% fields should state required or not in their schema
  35. Opts = #{atom_key => true, required => false},
  36. try
  37. {ok, hocon_tconf:check_plain(SchemaModule, Conf, Opts)}
  38. catch
  39. throw:Reason ->
  40. {error, Reason}
  41. end;
  42. check(SchemaModule, HoconText) ->
  43. case hocon:binary(HoconText, #{format => map}) of
  44. {ok, MapConfig} ->
  45. check(SchemaModule, MapConfig);
  46. {error, Reason} ->
  47. {error, Reason}
  48. end.
  49. %% Ensure iolist()
  50. iol(B) when is_binary(B) -> B;
  51. iol(A) when is_atom(A) -> atom_to_binary(A, utf8);
  52. iol(L) when is_list(L) -> L.