From c770db974554c6d992710dbbea01fc1edd87a777 Mon Sep 17 00:00:00 2001 From: Shawn <506895667@qq.com> Date: Fri, 18 Jun 2021 21:29:43 +0800 Subject: [PATCH] fix(richmap): hocon_schmea:richmap_to_map/1 failed on atom_key maps --- src/hocon_schema.erl | 21 ++++++++++++++------- test/hocon_schema_tests.erl | 11 ++++++++++- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/hocon_schema.erl b/src/hocon_schema.erl index 00ccc91..2cdeda8 100644 --- a/src/hocon_schema.erl +++ b/src/hocon_schema.erl @@ -88,6 +88,7 @@ -type loggerfunc() :: fun((atom(), map()) -> ok). -type opts() :: #{ logger => loggerfunc() , atom_key => boolean() + , return_plain => boolean() %% By default allow all fields to be undefined. %% if `nullable` is set to `false` %% map or check APIs fail with validation_error. @@ -255,7 +256,7 @@ check(Schema, Conf) -> check(Schema, Conf, #{}). check(Schema, Conf, Opts0) -> - Opts = maps:merge(#{atom_key => false}, Opts0), + Opts = maps:merge(#{is_richmap => true, atom_key => false}, Opts0), do_check(Schema, Conf, Opts, all). %% @doc Check plain-map input against schema. @@ -282,12 +283,18 @@ do_check(Schema, Conf, Opts0, RootNames) -> Opts = maps:merge(#{nullable => false}, Opts0), %% discard mappings for check APIs {_DiscardMappings, NewConf} = map(Schema, Conf, RootNames, Opts), - case maps:get(atom_key, Opts) of - true -> - atom_key_map(NewConf); - false -> - NewConf - end. + maybe_covert_keys_to_atom( + maybe_convert_to_plain_map(NewConf, Opts), Opts). + +maybe_convert_to_plain_map(Conf, #{is_richmap := true, return_plain := true}) -> + richmap_to_map(Conf); +maybe_convert_to_plain_map(Conf, _Opts) -> + Conf. + +maybe_covert_keys_to_atom(Conf, #{atom_key := true}) -> + atom_key_map(Conf); +maybe_covert_keys_to_atom(Conf, _Opts) -> + Conf. -spec map(schema(), hocon:config()) -> {[proplists:property()], hocon:config()}. map(Schema, Conf) -> diff --git a/test/hocon_schema_tests.erl b/test/hocon_schema_tests.erl index 836f8c1..d254693 100644 --- a/test/hocon_schema_tests.erl +++ b/test/hocon_schema_tests.erl @@ -201,7 +201,6 @@ richmap_to_map_test_() -> #{<<"b">> => [1, 2, #{<<"x">> => <<"foo">>}]}}, F("a.b = [1,2,{x=foo}]")) ]. - env_test_() -> F = fun (Str, Envs) -> {ok, M} = hocon:binary(Str, #{format => richmap}), @@ -297,6 +296,16 @@ atom_key_array_test() -> {ok, PlainMap} = hocon:binary(Conf, #{}), ?assertEqual(#{arr => [#{id => 1}, #{id => 2}]}, hocon_schema:check_plain(Sc, PlainMap, #{atom_key => true})). +return_plain_test() -> + Sc = #{structs => [?VIRTUAL_ROOT], + fields => [ {metadata, hoconsc:t(string())} + , {type, hoconsc:t(string())} + , {value, hoconsc:t(string())} + ]}, + StrConf = "type=t, metadata=m, value=v", + {ok, M} = hocon:binary(StrConf, #{format => richmap}), + ?assertMatch(#{metadata := "m", type := "t", value := "v"}, + hocon_schema:check(Sc, M, #{atom_key => true, return_plain => true})). validator_test() -> Sc = #{structs => [?VIRTUAL_ROOT],