Skip to content

Commit

Permalink
feat: percent support 12.345%
Browse files Browse the repository at this point in the history
  • Loading branch information
zhongwencool committed Dec 12, 2023
1 parent ebc78bb commit 7343f1c
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.eunit
.tool-versions
*.o
*.beam
*.plt
Expand Down
9 changes: 8 additions & 1 deletion sample-schemas/demo_schema.erl
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
-behaviour(hocon_schema).

-type duration() :: integer().
-type percent() :: float().

-typerefl_from_string({duration/0, emqx_schema, to_duration}).
-typerefl_from_string({percent/0, emqx_schema, to_percent}).

-reflect_type([duration/0]).
-reflect_type([duration/0, percent/0]).

-export([roots/0, fields/1, translations/0, translation/1]).

Expand All @@ -35,6 +37,7 @@ fields("a_b") ->
[ {"some_int", hoconsc:mk(integer(), #{mapping => "a_b.some_int",
importance => hidden
})}
, {"some_percent", fun some_percent/1}
];

fields("b") ->
Expand Down Expand Up @@ -112,6 +115,10 @@ numbers(_) -> undefined.
priv_duration(type) -> duration();
priv_duration(_) -> undefined.

some_percent(type) -> percent();
some_percent(mapping) -> "a_b.some_percent";
some_percent(_) -> undefined.

priv_bool(type) -> boolean();
priv_bool(_) -> undefined.

Expand Down
7 changes: 5 additions & 2 deletions src/hocon_postprocess.erl
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,13 @@ percent(Other) ->
Other.

do_percent(Str) ->
{ok, MP} = re:compile("([0-9]+)(%)$"),
{ok, MP} = re:compile("([0-9.]+)(%)$"),
case re_run_first(Str, MP) of
{match, [Val, _Unit]} ->
list_to_integer(Val) / 100;
case string:to_integer(Val) of
{Int, []} -> Int / 100;
_ -> round(list_to_float(Val) * 100) / 10000
end;
_ ->
Str
end.
Expand Down
12 changes: 12 additions & 0 deletions test/hocon_tconf_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,18 @@ mapping_test_() ->
F("foo.numbers=[1,2,3]")
),
?_assertEqual([{["a_b", "some_int"], 1}, Setting], F("a_b.some_int=1")),
?_assertEqual([{["a_b", "some_percent"], 0.12}, Setting], F("a_b.some_percent=12%")),
?_assertEqual([{["a_b", "some_percent"], 0.123}, Setting], F("a_b.some_percent=\"12.3%\"")),
?_assertEqual(
[{["a_b", "some_percent"], 0.1234}, Setting], F("a_b.some_percent=\"12.34%\"")
),
%% we only support 2 decimal places
?_assertEqual(
[{["a_b", "some_percent"], 0.4321}, Setting], F("a_b.some_percent=\"43.214%\"")
),
?_assertEqual(
[{["a_b", "some_percent"], 0.1235}, Setting], F("a_b.some_percent=\"12.345%\"")
),
?_assertEqual([Setting], F("foo.ref_x_y={some_int = 1}")),
?GEN_VALIDATION_ERR(_, F("foo.ref_x_y={some_int = aaa}")),
?_assertEqual(
Expand Down

0 comments on commit 7343f1c

Please sign in to comment.