Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
home:licehunter:staging
erlang-yval
_service:obs_scm:yval-1.0.10.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:yval-1.0.10.obscpio of Package erlang-yval
07070100000000000081A4000000000000000000000001627E5335000000B1000000000000000000000000000000000000001800000000yval-1.0.10/.travis.ymllanguage: erlang otp_release: - 19.3 - 22.1 install: - sudo apt-get -qq install libyaml-dev script: - make - make xref - make test notifications: email: false 07070100000001000081A4000000000000000000000001627E533500002C5E000000000000000000000000000000000000001400000000yval-1.0.10/LICENSE Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 07070100000002000081A4000000000000000000000001627E53350000018C000000000000000000000000000000000000001500000000yval-1.0.10/MakefileREBAR ?= rebar3 .PHONY: compile clean distclean xref dialyzer dialyze linter lint test all: compile compile: @$(REBAR) compile clean: @$(REBAR) clean distclean: clean rm -rf _build xref: @$(REBAR) xref dialyzer: @$(REBAR) dialyzer dialyze: @$(REBAR) dialyzer linter: @$(REBAR) as lint lint lint: @$(REBAR) as lint lint test: @$(REBAR) eunit --cover @$(REBAR) cover --verbose 07070100000003000081A4000000000000000000000001627E53350000098F000000000000000000000000000000000000001900000000yval-1.0.10/rebar.config{minimum_otp_vsn, "21.0"}. {erl_opts, [debug_info, warn_export_all, warn_export_vars, warn_missing_spec, warn_untyped_record, warn_unused_record, warn_bif_clash, warn_obsolete_guard, warn_unused_vars, warn_shadow_vars, warn_unused_import, warn_unused_function, warn_deprecated_function]}. {xref_checks, [undefined_function_calls, undefined_functions, locals_not_used, deprecated_function_calls, deprecated_functions]}. {dialyzer, [{warnings, [ unmatched_returns, error_handling, race_conditions, unknown ]} ]}. {elvis_output_format, plain}. {elvis, [#{dirs => ["."], filter => "rebar.config", rules => [{elvis_style, line_length, #{limit => 120, skip_comments => false}}, {elvis_style, no_tabs}, {elvis_style, no_trailing_whitespace}]}, #{dirs => ["src"], filter => "*.erl", rules => [{elvis_style, line_length, #{limit => 120, skip_comments => false}}, {elvis_style, no_tabs}, {elvis_style, no_trailing_whitespace}, {elvis_style, macro_module_names}, {elvis_style, operator_spaces, #{rules => [{right, ","}, {right, "++"}, {left, "++"}]}}, {elvis_style, used_ignored_variable}, {elvis_style, no_behavior_info}, {elvis_style, module_naming_convention, #{regex => "^([a-z][a-z0-9]*_?)*(_SUITE)?$"}}, {elvis_style, function_naming_convention, #{regex => "^[a-z][a-z0-9_]*$"}}, {elvis_style, state_record_and_type}, {elvis_style, no_spec_with_records}, {elvis_style, dont_repeat_yourself, #{min_complexity => 15}}, {elvis_style, no_debug_call, #{ignore => []}}, {elvis_style, no_common_caveats_call}]}, #{dirs => ["src"], filter => "*.app.src", rules => [{elvis_style, line_length, #{limit => 120, skip_comments => false}}, {elvis_style, no_tabs}, {elvis_style, no_trailing_whitespace}]}, #{dirs => ["."], filter => "Makefile", ruleset => makefiles} ]}. {profiles, [{test, [{erl_opts, [nowarn_export_all, nowarn_missing_spec]} ]}, {lint, [{plugins, [{rebar3_lint, "0.1.10"}]} ]} ]}. {project_plugins, [rebar3_ex_doc]}. {ex_doc, [{source_url, <<"https://github.com/processone/yval">>}, {extras, [<<"LICENSE">>]} ]}. {hex, [{doc, ex_doc} ]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: 07070100000004000041ED000000000000000000000002627E533500000000000000000000000000000000000000000000001000000000yval-1.0.10/src07070100000005000081A4000000000000000000000001627E53350000048C000000000000000000000000000000000000001D00000000yval-1.0.10/src/yval.app.src%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov <ekhramtsov@process-one.net> %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- {application, yval, [{description, "YAML validator"}, {vsn, "1.0.10"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib]}, {env, []}, %% hex.pm packaging: {licenses, ["Apache-2.0"]}, {links, [{"Github", "https://github.com/processone/yval"}]} ]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: 07070100000006000081A4000000000000000000000001627E53350000AA06000000000000000000000000000000000000001900000000yval-1.0.10/src/yval.erl%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov <ekhramtsov@process-one.net> %%% @copyright (C) 2002-2020 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -module(yval). %% API -export([validate/2, fail/2]). -export([format_error/1, format_error/2, format_ctx/1]). %% Simple types -export([pos_int/0, pos_int/1, non_neg_int/0, non_neg_int/1]). -export([int/0, int/2, number/1, number/2, pos_number/0, octal/0]). -export([binary/0, binary/1, binary/2]). -export([string/0, string/1, string/2]). -export([enum/1, bool/0, atom/0, any/0]). %% Complex types -export([url/0, url/1]). -export([file/0, file/1]). -export([directory/0, directory/1]). -export([ip/0, ipv4/0, ipv6/0, ip_mask/0, port/0]). -export([re/0, re/1, glob/0, glob/1]). -export([path/0, binary_sep/1]). -export([beam/0, beam/1, base64/0]). -export([hex/0]). -export([timeout/1, timeout/2]). -export([rfc3339_time/1]). -export([term/0, percent/0, percent/2]). %% Composite types -export([list/1, list/2]). -export([list_or_single/1, list_or_single/2]). -export([map/2, map/3]). -export([either/2, and_then/2, non_empty/1]). -export([options/1, options/2]). -define(is_validator(Term), is_function(Term, 1)). -type infinity() :: infinity | infinite | unlimited. -type timeout_unit() :: millisecond | second | minute | hour | day. -type time_unit() :: microsecond | millisecond | nanosecond | second. -type exports() :: [{atom(), arity()} | [{atom(), arity()}]]. -type options() :: [{atom(), term()}] | #{atom() => term()} | dict:dict(atom(), term()). -type return_type() :: list | map | dict | orddict. -type unique_opt() :: unique | {unique, boolean()}. -type sorted_opt() :: sorted | {sorted, boolean()}. -type ctx() :: [atom() | binary() | integer()]. -type yaml_val() :: atom() | number() | binary(). -type yaml_list() :: [yaml()]. -type yaml_map() :: [{yaml_val(), yaml()}]. -type yaml() :: yaml_val() | yaml_list() | yaml_map(). -type validator_option() :: {required, [atom()]} | {defaults, #{atom() => term()}} | {disallowed, [atom()]} | unique | {unique, boolean()} | {return, return_type()}. -type validator() :: fun((yaml()) -> term()). -type validator(T) :: fun((yaml()) -> T). -type validators() :: #{atom() => validator()}. -type error_reason() :: term(). -type error_return() :: {error, error_reason(), ctx()}. -export_type([validator/0, validator/1, validators/0, validator_option/0]). -export_type([error_return/0, error_reason/0, ctx/0]). %%%=================================================================== %%% API %%%=================================================================== -spec validate(validator(), yaml()) -> {ok, any()} | error_return(). validate(Validator, Y) -> try {ok, Validator(Y)} catch _:{?MODULE, Why, Ctx} -> {error, Why, Ctx}; Class:Reason:Stacktrace -> _ = erase_ctx(), erlang:raise(Class, Reason, Stacktrace) end. -spec fail(module(), term()) -> no_return(). fail(Mod, Reason) -> fail({Mod, Reason}). %%%=================================================================== %%% Validators %%%=================================================================== -spec enum([atom() | binary()]) -> validator(atom() | binary()). enum([H|_] = List) when is_atom(H); is_binary(H) -> fun(Val) -> Member = if is_binary(H) -> to_binary(Val); is_atom(H) -> to_existing_atom(Val) end, case lists:member(Member, List) of true -> Member; false -> fail({bad_enum, List, Member}) end end. -spec bool() -> validator(boolean()). bool() -> fun(Val) -> case to_existing_atom(Val) of on -> true; off -> false; yes -> true; no -> false; y -> true; n -> false; true -> true; false -> false; Bad -> fail({bad_bool, Bad}) end end. -spec pos_int() -> validator(pos_integer()). pos_int() -> fun(Val) -> case to_int(Val) of I when I>0 -> I; Bad -> fail({bad_pos_int, Bad}) end end. -spec pos_int(infinity()) -> validator(pos_integer() | infinity()). pos_int(Inf) when Inf == infinity; Inf == infinite; Inf == unlimited -> fun(Val) -> case to_int(Val, Inf) of I when I>0 -> I; Bad -> fail({bad_pos_int, Inf, Bad}) end end. -spec non_neg_int() -> validator(non_neg_integer()). non_neg_int() -> fun(Val) -> case to_int(Val) of I when I>=0 -> I; Bad -> fail({bad_non_neg_int, Bad}) end end. -spec non_neg_int(infinity()) -> validator(non_neg_integer() | infinity()). non_neg_int(Inf) when Inf == infinity; Inf == infinite; Inf == unlimited -> fun(Val) -> case to_int(Val, Inf) of I when I>=0 -> I; Bad -> fail({bad_non_neg_int, Inf, Bad}) end end. -spec int() -> validator(integer()). int() -> fun to_int/1. -spec int(integer(), integer() | infinity) -> validator(integer()). int(Min, Max) when is_integer(Min) andalso (is_integer(Max) orelse Max == infinity) andalso Min =< Max -> fun(Val) -> case to_int(Val) of I when I>=Min, I=<Max -> I; Bad -> fail({bad_int, Min, Max, Bad}) end end. -spec number(number()) -> validator(number()). number(Min) -> number(Min, infinity). -spec number(number(), number() | infinity) -> validator(number()). number(Min, Max) when is_number(Min) andalso (is_number(Max) orelse Max == infinity) andalso Min =< Max -> fun(Val) -> case to_number(Val) of N when N >= Min, N =< Max -> N; Bad -> fail({bad_number, Min, Max, Bad}) end end. -spec pos_number() -> validator(number()). pos_number() -> fun(Val) -> case to_number(Val) of N when N>0 -> N; Bad -> fail({bad_pos_number, Bad}) end end. -spec percent() -> validator(number()). percent() -> percent(0.0, 1.0). -spec percent(number(), number() | infinity) -> validator(number()). percent(Min, Max) -> fun(Val) when is_number(Val) -> (number(Min, Max))(Val); (Val) -> case string:trim(to_string(Val)) of "" -> fail(empty_string); S -> case lists:reverse(S) of [$%|T] -> Num = string_to_number(string:trim(lists:reverse(T)))/100, (number(Min, Max))(Num); _ -> fail({bad_number, list_to_binary(S)}) end end end. -spec binary() -> validator(binary()). binary() -> fun to_binary/1. -spec binary(iodata()) -> validator(binary()). binary(Regexp) -> binary(Regexp, [unicode]). -spec binary(iodata(), [proplists:property()]) -> validator(binary()). binary(Regexp, Opts) when is_list(Regexp) orelse is_binary(Regexp) -> {ok, Re} = re:compile(Regexp, Opts), fun(Val) -> Bin = to_binary(Val), case re:run(Bin, Re) of {match, _} -> Bin; nomatch -> case lists:member(unicode, Opts) of true -> case is_unicode(Bin, utf8) of true -> fail({nomatch, Regexp, Bin}); false -> fail({bad_unicode, Bin}) end; false -> fail({nomatch, Regexp, Bin}) end end end. -spec atom() -> validator(atom()). atom() -> fun to_atom/1. -spec string() -> validator(string()). string() -> fun to_string/1. -spec string(iodata()) -> validator(string()). string(Regexp) -> string(Regexp, [unicode]). -spec string(iodata(), [proplists:property()]) -> validator(string()). string(Regexp, Opts) when is_list(Regexp) orelse is_binary(Regexp) -> and_then( binary(Regexp, Opts), fun binary_to_list/1). -spec term() -> validator(term()). term() -> fun(Val) -> case string:trim(to_string(Val)) of "" -> fail(empty_string); Str1 -> Str2 = case lists:last(Str1) of $. -> Str1; _ -> Str1 ++ "." end, case erl_scan:string(Str2) of {ok, Tokens, _} -> case erl_parse:parse_term(Tokens) of {ok, Term} -> Term; {error, Reason} -> fail({bad_term, Reason}) end; {error, Reason, _} -> fail({bad_term, Reason}) end end end. -spec binary_sep(iodata()) -> validator([binary()]). binary_sep(Sep) -> fun(Val) -> Bin = to_binary(Val), lists:filtermap( fun(<<>>) -> false; (S) -> {true, S} end, re:split(Bin, Sep)) end. -spec path() -> validator(binary()). path() -> fun prep_path/1. -spec file() -> validator(binary()). file() -> file(read). -spec file(read | write) -> validator(binary()). file(read) -> fun(Val) -> Path = prep_path(Val), case file:open(Path, [read]) of {ok, Fd} -> _ = file:close(Fd), Path; {error, Why} -> fail({read_file, Why, Path}) end end; file(write) -> fun(Val) -> Path = prep_path(Val), case filelib:ensure_dir(Path) of ok -> case file:open(Path, [append]) of {ok, Fd} -> _ = file:close(Fd), Path; {error, Why} -> fail({create_file, Why, Path}) end; {error, Why} -> fail({create_dir, Why, filename:dirname(Path)}) end end. -spec directory() -> validator(binary()). directory() -> directory(read). -spec directory(read | write) -> validator(binary()). directory(read) -> fun(Val) -> Path = prep_path(Val), case filelib:is_dir(Path) of true -> Path; false -> case file:list_dir(Path) of {error, Why} -> fail({read_dir, Why, Path}); {ok, _} -> Path end end end; directory(write) -> fun(Val) -> Path = prep_path(Val), case filelib:ensure_dir(filename:join(Path, "foo")) of ok -> Path; {error, Why} -> fail({create_dir, Why, Path}) end end. -spec url() -> validator(binary()). url() -> url([http, https]). -spec url([atom()]) -> validator(binary()). url(Schemes0) -> Schemes = [atom_to_binary(S, latin1) || S <- Schemes0], fun(Val) -> URL = to_binary(Val), case uri_string:parse(URL) of #{port := Port} when Port < 1; Port > 65535 -> fail({bad_url, bad_port, URL}); #{} = Parsed -> case {maps:get(scheme, Parsed, <<>>), maps:get(host, Parsed, <<>>)} of {<<>>, _} -> fail({bad_url, no_scheme, URL}); {_, <<>>} -> fail({bad_url, empty_host, URL}); {Scheme, _} when Schemes /= [] -> case lists:member(Scheme, Schemes) of true -> URL; false -> fail({bad_url, {unsupported_scheme, Scheme}, URL}) end; {_, _} -> URL end; {error, Why, _Info} -> fail({bad_url, Why, URL}) end end. -spec octal() -> validator(non_neg_integer()). octal() -> fun(Val) -> Bin = to_binary(Val), try binary_to_integer(Bin, 8) catch _:_ -> fail({bad_octal, Bin}) end end. -spec ipv4() -> validator(inet:ip4_address()). ipv4() -> fun(Val) -> S = to_string(Val), case inet:parse_ipv4_address(to_string(Val)) of {ok, IP} -> IP; _ -> fail({bad_ipv4, S}) end end. -spec ipv6() -> validator(inet:ip6_address()). ipv6() -> fun(Val) -> S = to_string(Val), case inet:parse_ipv6strict_address(S) of {ok, IP} -> IP; _ -> fail({bad_ipv6, S}) end end. -spec ip() -> validator(inet:ip_address()). ip() -> fun(Val) -> S = to_string(Val), case inet:parse_address(S) of {ok, IP} -> IP; _ -> fail({bad_ip, S}) end end. -spec ip_mask() -> validator( {inet:ip4_address(), 0..32} | {inet:ip6_address(), 0..128}). ip_mask() -> fun(Val) -> S = to_string(Val), case parse_ip_netmask(S) of {ok, IP, Mask} -> {IP, Mask}; _ -> fail({bad_ip_mask, S}) end end. -spec port() -> validator(1..65535). port() -> int(1, 65535). -spec timeout(timeout_unit()) -> validator(pos_integer()). timeout(Unit) -> fun(Val) -> to_timeout(Val, Unit) end. -spec timeout(timeout_unit(), infinity()) -> validator(pos_integer() | infinity()). timeout(Unit, Inf) -> fun(Val) -> to_timeout(Val, Unit, Inf) end. -spec rfc3339_time(time_unit()) -> validator(non_neg_integer()). rfc3339_time(Unit) -> fun(Val) -> S = to_string(Val), try calendar:rfc3339_to_system_time(S, [{unit, Unit}]) of Int -> Int catch _:_ -> fail({bad_rfc3339_time, S}) end end. -spec re() -> validator(). re() -> re([unicode]). -spec re([proplists:property()]) -> validator(). re(Opts) -> fun(Val) -> Bin = to_binary(Val), case re:compile(Bin, Opts) of {ok, RE} -> RE; {error, Why} -> fail({bad_regexp, Why, Bin}) end end. -spec glob() -> validator(). glob() -> glob([]). -spec glob([proplists:property()]) -> validator(). glob(Opts) -> fun(Val) -> S = to_string(Val), case re:compile(sh_to_awk(S), Opts) of {ok, RE} -> RE; {error, Why} -> fail({bad_glob, Why, S}) end end. -spec beam() -> validator(module()). beam() -> beam([]). -spec beam(exports()) -> validator(module()). beam(Exports) -> fun(Val) -> Mod = to_atom(Val), case code:ensure_loaded(Mod) of {module, Mod} -> lists:foreach( fun([]) -> ok; (L) when is_list(L) -> case lists:any( fun({F, A}) -> erlang:function_exported(Mod, F, A) end, L) of true -> ok; false -> fail({bad_export, hd(L), Mod}) end; ({F, A}) -> case erlang:function_exported(Mod, F, A) of true -> ok; false -> fail({bad_export, {F, A}, Mod}) end end, Exports), Mod; _ -> fail({bad_module, Mod}) end end. -spec base64() -> validator(binary()). base64() -> fun(Val) -> B = to_binary(Val), try base64:decode(B) catch _:_ -> fail({bad_base64, B}) end end. -spec hex() -> validator(binary()). hex() -> fun(Val) -> B = to_binary(Val), try from_hex(B) catch _:_ -> fail({bad_hex, B}) end end. -spec non_empty(validator(T)) -> validator(T). non_empty(Fun) -> fun(Val) -> case Fun(Val) of '' -> fail(empty_atom); <<"">> -> fail(empty_binary); [] -> fail(empty_list); Ret -> Ret end end. -spec list(validator(T)) -> validator([T]). list(Fun) -> list(Fun, []). -spec list(validator(T), [unique_opt() | sorted_opt()]) -> validator([T]). list(Fun, Opts) when ?is_validator(Fun) -> fun(L) when is_list(L) -> {L1, _} = lists:mapfoldl( fun(Val, Pos) -> Ctx = get_ctx(), put_ctx([Pos|Ctx]), Val1 = Fun(Val), put_ctx(Ctx), {Val1, Pos+1} end, 1, L), L2 = unique(L1, Opts), case proplists:get_bool(sorted, Opts) of true -> lists:sort(L2); false -> L2 end; (Bad) -> fail({bad_list, Bad}) end. -spec list_or_single(validator(T)) -> validator([T]). list_or_single(Fun) -> list_or_single(Fun, []). -spec list_or_single(validator(T), [unique_opt() | sorted_opt()]) -> validator([T]). list_or_single(Fun, Opts) when ?is_validator(Fun) -> fun(L) when is_list(L) -> (list(Fun, Opts))(L); (V) -> [Fun(V)] end. -spec map(validator(T1), validator(T2)) -> validator([{T1, T2}] | #{T1 => T2}). map(Fun1, Fun2) -> map(Fun1, Fun2, [{return, list}]). -spec map(validator(T1), validator(T2), [{return, return_type()} | unique_opt()]) -> validator([{T1, T2}] | #{T1 => T2} | dict:dict(T1, T2)). map(Fun1, Fun2, Opts) when ?is_validator(Fun1) andalso ?is_validator(Fun2) -> fun(L) when is_list(L) -> M1 = lists:map( fun({Key, Val}) -> Key1 = Fun1(Key), Ctx = get_ctx(), put_ctx([Key|Ctx]), Val1 = Fun2(Val), put_ctx(Ctx), {Key1, Val1}; (_) -> fail({bad_map, L}) end, L), M2 = unique(M1, Opts), case proplists:get_value(return, Opts, list) of list -> M2; map -> maps:from_list(M2); orddict -> orddict:from_list(M2); dict -> dict:from_list(M2) end; (Bad) -> fail({bad_map, Bad}) end. -spec either(atom(), validator(T)) -> validator(atom() | T); (validator(T1), validator(T2)) -> validator(T1 | T2). either(Atom, Fun) when is_atom(Atom) andalso ?is_validator(Fun) -> either(enum([Atom]), Fun); either(Fun1, Fun2) when ?is_validator(Fun1) andalso ?is_validator(Fun2) -> fun(Val) -> Ctx = get_ctx(), try Fun1(Val) catch _:_ -> put_ctx(Ctx), Fun2(Val) end end. -spec and_then(validator(T1), fun((T1) -> T2)) -> validator(T2). and_then(Fun, Then) when ?is_validator(Fun) andalso is_function(Then, 1) -> fun(Val) -> Then(Fun(Val)) end. -spec any() -> validator(yaml()). any() -> fun(Val) -> Val end. -spec options(validators()) -> validator(). options(Validators) -> options(Validators, [unique]). -spec options(validators(), [validator_option()]) -> validator(). options(Validators, Options) -> fun(Opts) when is_list(Opts) -> Required = proplists:get_value(required, Options, []), Defaults = proplists:get_value(defaults, Options, #{}), Disallowed = proplists:get_value(disallowed, Options, []), CheckDups = proplists:get_bool(unique, Options), Return = proplists:get_value(return, Options, list), DefaultValidator = maps:get('_', Validators, undefined), validate_options(Opts, Validators, DefaultValidator, Required, Defaults, Disallowed, CheckDups, Return); (Bad) -> fail({bad_map, Bad}) end. %%%=================================================================== %%% Formatters %%%=================================================================== -spec format_error(error_reason(), ctx()) -> string(). format_error(Why, []) -> format_error(Why); format_error(Why, Ctx) -> format_ctx(Ctx) ++ ": " ++ format_error(Why). -spec format_error(error_reason()) -> string(). format_error({bad_atom, Bad}) -> format("Expected string, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_binary, Bad}) -> format("Expected string, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_unicode, _}) -> "Non UTF-8 string"; format_error({bad_bool, Bad}) -> format("Expected boolean, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_base64, _}) -> format("Invalid Base64 string", []); format_error({bad_hex, _}) -> format("Invalid hexadecimal string", []); format_error({bad_cwd, Why}) -> format("Failed to get current directory name: ~s", [file:format_error(Why)]); format_error({bad_enum, _Known, Bad}) -> format("Unexpected value: ~s", [Bad]); format_error({bad_export, {F, A}, Mod}) -> format("Module '~s' doesn't export function ~s/~B", [Mod, F, A]); format_error({bad_glob, {Reason, _}, _}) -> format("Invalid glob expression: ~s", [Reason]); format_error({bad_int, Bad}) -> format("Expected integer, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_int, Min, infinity, Bad}) -> format("Expected integer >= ~B, got: ~B", [Min, Bad]); format_error({bad_int, Min, Max, Bad}) -> format("Expected integer from ~B to ~B, got: ~B", [Min, Max, Bad]); format_error({bad_ip_mask, S}) -> format("Invalid IP address or network mask: ~s", [S]); format_error({bad_ip, S}) -> format("Invalid IP address: ~s", [S]); format_error({bad_ipv4, S}) -> format("Invalid IPv4 address: ~s", [S]); format_error({bad_ipv6, S}) -> format("Invalid IPv6 address: ~s", [S]); format_error({bad_length, Limit}) -> format("The value must not exceed ~B octets in length", [Limit]); format_error({bad_list, Bad}) -> format("Expected list, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_map, Bad}) -> format("Expected map, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_module, Mod}) -> format("Unknown module: ~s", [Mod]); format_error({bad_non_neg_int, Bad}) -> format("Expected non negative integer, got: ~B", [Bad]); format_error({bad_non_neg_int, Inf, Bad}) -> format("Expected non negative integer or '~s', got: ~B", [Inf, Bad]); format_error({bad_number, Bad}) -> format("Expected number, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_number, Min, infinity, Bad}) -> format("Expected number >= ~p, got: ~p", [Min, Bad]); format_error({bad_number, Min, Max, Bad}) -> format("Expected number from ~p to ~p, got: ~p", [Min, Max, Bad]); format_error({bad_pos_number, Bad}) -> format("Expected positive number, got: ~p", [Bad]); format_error({bad_octal, Bad}) -> format("Expected octal, got: ~s", [Bad]); format_error({bad_pos_int, Bad}) -> format("Expected positive integer, got: ~B", [Bad]); format_error({bad_pos_int, Inf, Bad}) -> format("Expected positive integer or '~s', got: ~B", [Inf, Bad]); format_error({bad_regexp, {Reason, _}, _}) -> format("Invalid regular expression: ~s", [Reason]); format_error({bad_timeout, Bad}) -> format("Expected positive integer, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_timeout, Inf, Bad}) -> format("Expected positive integer or '~s', got ~s instead", [Inf, format_yaml_type(Bad)]); format_error({bad_timeout_unit, Bad}) -> format("Unexpected timeout unit: ~s", [Bad]); format_error({bad_timeout_min, Unit}) -> format("Timeout must not be shorter than one ~s", [Unit]); format_error({bad_rfc3339_time, S}) -> format("Expected RFC 3339 timestamp, got: ~s", [S]); format_error({bad_url, empty_host, URL}) -> format("Empty hostname in the URL: ~s", [URL]); format_error({bad_url, no_scheme, URL}) -> format("No scheme in the URL: ~s", [URL]); format_error({bad_url, {unsupported_scheme, Scheme}, URL}) -> format("Unsupported scheme '~s' in the URL: ~s", [Scheme, URL]); format_error({bad_url, bad_port, URL}) -> format("Invalid port number in the URL: ~s", [URL]); format_error({bad_url, _, URL}) -> format("Invalid URL: ~s", [URL]); format_error({bad_term, {LineNo, Module, Reason}}) -> format("Invalid Erlang term: at line ~B: ~s", [LineNo, Module:format_error(Reason)]); format_error({create_dir, Why, Path}) -> format("Failed to create directory '~s': ~s", [Path, file:format_error(Why)]); format_error({create_file, Why, Path}) -> format("Failed to open file '~s' for writing: ~s", [Path, file:format_error(Why)]); format_error({disallowed_option, Opt}) -> format("Parameter '~s' is not allowed in this context", [Opt]); format_error({duplicated_key, Key}) -> format("Duplicated key: ~s", [format_yaml(Key)]); format_error({duplicated_value, Val}) -> format("Duplicated value: ~s", [format_yaml(Val)]); format_error({duplicated_option, Opt}) -> format("Duplicated parameter: ~s", [Opt]); format_error(empty_atom) -> format("Empty string is not allowed", []); format_error(empty_binary) -> format("Empty string is not allowed", []); format_error(empty_list) -> format("Empty list is not allowed", []); format_error(empty_string) -> format("Empty string is not allowed", []); format_error({missing_option, Opt}) -> format("Missing required parameter: ~s", [Opt]); format_error({nomatch, Regexp, Data}) -> format("String '~s' doesn't match regular expression: ~s", [Data, Regexp]); format_error({read_dir, Why, Path}) -> format("Failed to read directory '~s': ~s", [Path, file:format_error(Why)]); format_error({read_file, Why, Path}) -> format("Failed to read file '~s': ~s", [Path, file:format_error(Why)]); format_error({unknown_option, _Known, Opt}) -> format("Unknown parameter: ~s", [Opt]); format_error({Mod, Reason}) when is_atom(Mod) -> Mod:format_error(Reason); format_error(Unexpected) -> format("Unexpected error reason: ~p", [Unexpected]). -spec format_ctx(ctx()) -> string(). format_ctx([]) -> "Validation error"; format_ctx([_|_] = Ctx) -> format("Invalid value of parameter '~s'", [string:join( lists:map( fun(A) when is_atom(A) -> atom_to_list(A); (B) when is_binary(B) -> "'" ++ binary_to_list(B) ++ "'"; (I) when is_integer(I) -> integer_to_list(I); (Unexpected) -> lists:flatten(io_lib:format("~p", [Unexpected])) end, Ctx), "->")]). -spec format(iodata(), list()) -> string(). format(Fmt, Args) -> lists:flatten(io_lib:format(Fmt, Args)). -spec format_yaml_type(yaml()) -> string(). format_yaml_type(<<>>) -> "empty string"; format_yaml_type('') -> "empty string"; format_yaml_type([]) -> "empty list"; format_yaml_type(I) when is_integer(I) -> "integer"; format_yaml_type(N) when is_number(N) -> "number"; format_yaml_type(B) when is_binary(B) -> "string"; format_yaml_type(A) when is_atom(A) -> "string"; format_yaml_type([{_, _}|_]) -> "map"; format_yaml_type([_|_]) -> "list"; format_yaml_type(Unexpected) -> lists:flatten(io_lib:format("~p", [Unexpected])). -spec format_yaml(yaml()) -> iodata(). format_yaml(I) when is_integer(I) -> integer_to_list(I); format_yaml(B) when is_atom(B) -> try erlang:atom_to_binary(B, latin1) catch _:badarg -> erlang:atom_to_binary(B, utf8) end; format_yaml(Y) -> S = try iolist_to_binary(Y) catch _:_ -> list_to_binary(io_lib:format("~p", [Y])) end, case binary:match(S, <<"\n">>) of nomatch -> S; _ -> [io_lib:nl(), S] end. %%%=================================================================== %%% Internal functions %%%=================================================================== %%%=================================================================== %%% Auxiliary functions %%%=================================================================== -spec to_binary(term()) -> binary(). to_binary(A) when is_atom(A) -> atom_to_binary(A, latin1); to_binary(B) when is_binary(B) -> B; to_binary(Bad) -> fail({bad_binary, Bad}). -spec to_atom(term()) -> atom(). to_atom(B) when is_binary(B) -> try binary_to_atom(B, latin1) catch _:system_limit -> fail({bad_length, 255}) end; to_atom(A) when is_atom(A) -> A; to_atom(Bad) -> fail({bad_atom, Bad}). -spec to_existing_atom(term()) -> atom() | binary(). to_existing_atom(B) when is_binary(B) -> try binary_to_existing_atom(B, latin1) catch _:_ -> B end; to_existing_atom(A) -> to_atom(A). -spec to_string(term()) -> string(). to_string(A) when is_atom(A) -> atom_to_list(A); to_string(S) -> binary_to_list(to_binary(S)). -spec from_hex(binary()) -> binary(). from_hex(B) when (size(B) rem 2) == 0 -> << <<(hexchar_to_digit(Hi)*16 + hexchar_to_digit(Lo))>> || <<Hi, Lo>> <= B >>. -spec hexchar_to_digit(char()) -> byte(). hexchar_to_digit(C) when C >= $0 andalso C =< $9 -> C - $0; hexchar_to_digit(C) when C >= $a andalso C =< $f -> C - 87; hexchar_to_digit(C) when C >= $A andalso C =< $F -> C - 55. -spec to_int(term()) -> integer(). to_int(I) when is_integer(I) -> I; to_int(Bad) -> fail({bad_int, Bad}). -spec to_int(term(), infinity()) -> integer() | infinity(). to_int(I, _) when is_integer(I) -> I; to_int(infinity, Inf) -> Inf; to_int(infinite, Inf) -> Inf; to_int(unlimited, Inf) -> Inf; to_int(B, Inf) when is_binary(B) -> try binary_to_existing_atom(B, latin1) of A -> to_int(A, Inf) catch _:_ -> fail({bad_int, B}) end; to_int(Bad, _) -> fail({bad_int, Bad}). -spec to_number(term()) -> number(). to_number(N) when is_number(N) -> N; to_number(Bad) -> fail({bad_number, Bad}). -spec to_timeout(term(), timeout_unit()) -> pos_integer() | infinity(). to_timeout(Term, Unit) -> to_timeout(Term, Unit, undefined). -spec to_timeout(term(), timeout_unit(), infinity() | undefined) -> pos_integer() | infinity(). to_timeout(I, Unit, Inf) when is_integer(I) -> if I>0 -> to_ms(I, Unit); Inf == undefined -> fail({bad_pos_int, I}); true -> fail({bad_pos_int, Inf, I}) end; to_timeout(A, Unit, Inf) when is_atom(A) -> to_timeout(atom_to_binary(A, latin1), Unit, Inf); to_timeout(B, Unit, Inf) when is_binary(B) -> S = binary_to_list(B), case string:to_integer(S) of {error, _} when Inf /= undefined -> _ = (enum([infinite, infinity, unlimited]))(B), Inf; {error, _} -> fail({bad_int, B}); {I, ""} when is_integer(I), I>0 -> to_ms(I, Unit); {I, [_|_] = Suffix} when is_integer(I), I>0 -> case timeout_unit(Suffix) of {ok, Unit1} -> to_ms(I, Unit1, Unit); error -> fail({bad_timeout_unit, Suffix}) end; {I, _} when Inf == undefined -> fail({bad_pos_int, I}); {I, _} -> fail({bad_pos_int, Inf, I}) end; to_timeout(Bad, _, Inf) when Inf == undefined -> fail({bad_timeout, Bad}); to_timeout(Bad, _, Inf) -> fail({bad_timeout, Inf, Bad}). -spec to_ms(pos_integer(), timeout_unit()) -> pos_integer(). to_ms(I, Unit) -> case Unit of millisecond -> I; second -> timer:seconds(I); minute -> timer:minutes(I); hour -> timer:hours(I); day -> timer:hours(I*24) end. -spec to_ms(pos_integer(), timeout_unit(), timeout_unit()) -> pos_integer(). to_ms(I, Unit, MinUnit) -> MSecs = to_ms(I, Unit), case MSecs >= to_ms(1, MinUnit) of true -> MSecs; false -> fail({bad_timeout_min, MinUnit}) end. -spec timeout_unit(string()) -> {ok, timeout_unit()} | error. timeout_unit(S) -> U = string:strip(string:to_lower(S), both, $ ), if U == "ms"; U == "msec"; U == "msecs"; U == "millisec"; U == "millisecs"; U == "millisecond"; U == "milliseconds" -> {ok, millisecond}; U == "s"; U == "sec"; U == "secs"; U == "second"; U == "seconds" -> {ok, second}; U == "m"; U == "min"; U == "mins"; U == "minute"; U == "minutes" -> {ok, minute}; U == "h"; U == "hour"; U == "hours" -> {ok, hour}; U == "d"; U == "day"; U == "days" -> {ok, day}; true -> error end. -spec is_unicode(binary(), unicode:encoding()) -> boolean(). is_unicode(Bin, Encoding) -> try unicode:characters_to_list(Bin, Encoding) of L when is_list(L) -> true; _ -> false catch _:_ -> false end. -spec unique(list(T), [proplists:property()]) -> list(T). unique(L, Opts) -> case proplists:get_bool(unique, Opts) of true -> unique(L); false -> L end. -spec unique(list(T)) -> list(T). unique([{_, _}|_] = Map) -> lists:foldr( fun({K, V}, Acc) -> case lists:keymember(K, 1, Acc) of true -> fail({duplicated_key, K}); false -> [{K, V}|Acc] end end, [], Map); unique(L) -> lists:foldr( fun(X, Acc) -> case lists:member(X, Acc) of true -> fail({duplicated_value, X}); false -> [X|Acc] end end, [], L). -spec string_to_number(string()) -> number(). string_to_number(S) -> try erlang:list_to_integer(S) of Int -> Int catch _:badarg -> try erlang:list_to_float(S) of Float -> Float catch _:badarg -> fail({bad_number, list_to_binary(S)}) end end. -spec parse_ip_netmask(string()) -> {ok, inet:ip4_address(), 0..32} | {ok, inet:ip6_address(), 0..128} | error. parse_ip_netmask(S) -> case string:tokens(S, "/") of [IPStr] -> case inet:parse_address(IPStr) of {ok, {_, _, _, _} = IP} -> {ok, IP, 32}; {ok, {_, _, _, _, _, _, _, _} = IP} -> {ok, IP, 128}; _ -> error end; [IPStr, MaskStr] -> try list_to_integer(MaskStr) of Mask when Mask >= 0 -> case inet:parse_address(IPStr) of {ok, {_, _, _, _} = IP} when Mask =< 32 -> {ok, IP, Mask}; {ok, {_, _, _, _, _, _, _, _} = IP} when Mask =< 128 -> {ok, IP, Mask}; _ -> error end; _ -> error catch _:_ -> error end; _ -> error end. -spec fail(error_reason()) -> no_return(). fail(Reason) -> erlang:nif_error({?MODULE, Reason, erase_ctx()}). -spec prep_path(term()) -> binary(). prep_path(Path0) -> Path1 = (non_empty(binary()))(Path0), case filename:pathtype(Path1) of relative -> case file:get_cwd() of {ok, CWD} -> filename:join( unicode:characters_to_binary(CWD), Path1); {error, Reason} -> fail({bad_cwd, Reason}) end; _ -> Path1 end. -spec validate_options(list(), validators(), validator() | undefined, [atom()], #{atom() => term()}, [atom()], boolean(), return_type()) -> options(). validate_options(Opts, Validators, DefaultValidator, Required, Defaults, Disallowed, CheckDups, Return) -> validate_options(Opts, Validators, DefaultValidator, Required, Defaults, Disallowed, CheckDups, Return, []). -spec validate_options(list(), validators(), validator() | undefined, [atom()], #{atom() => term()}, [atom()], boolean(), return_type(), options()) -> options(). validate_options([{O, Val}|Opts], Validators, DefaultValidator, Required, Defaults, Disallowed, CheckDups, Return, Acc) -> Opt = to_existing_atom(O), case lists:member(Opt, Disallowed) of true -> fail({disallowed_option, Opt}); false -> case maps:get(Opt, Validators, DefaultValidator) of undefined -> Allowed = maps:keys(Validators) -- Disallowed, fail({unknown_option, Allowed, Opt}); Validator when is_atom(Opt) -> case CheckDups andalso lists:keymember(Opt, 1, Acc) of true -> fail({duplicated_option, Opt}); false -> Required1 = proplists:delete(Opt, Required), Acc1 = [{Opt, validate_option(Opt, Val, Validator)}|Acc], validate_options(Opts, Validators, DefaultValidator, Required1, Defaults, Disallowed, CheckDups, Return, Acc1) end; _ -> validate_options(Opts, Validators, DefaultValidator, Required, Defaults, Disallowed, CheckDups, Return, Acc) end end; validate_options([], _, _, [], Defaults, _, _, Return, Acc) -> case Return of list -> apply_defaults(lists:reverse(Acc), Defaults); map -> maps:merge(Defaults, maps:from_list(Acc)); dict -> dict:from_list(apply_defaults(Acc, Defaults)); orddict -> orddict:from_list(apply_defaults(Acc, Defaults)) end; validate_options([], _, _, [Required|_], _, _, _, _, _) -> fail({missing_option, Required}); validate_options(Bad, _, _, _, _, _, _, _, _) -> fail({bad_map, Bad}). -spec validate_option(atom(), yaml(), validator(T)) -> T. validate_option(Opt, Val, Validator) -> Ctx = get_ctx(), put_ctx([Opt|Ctx]), Ret = Validator(Val), put_ctx(Ctx), Ret. -spec apply_defaults([{atom(), T}], #{atom() => T}) -> [{atom(), T}]. apply_defaults(Opts, Defaults) -> case maps:size(Defaults) of 0 -> Opts; _ -> Rest = lists:foldl( fun({Opt, _}, Acc) -> maps:remove(Opt, Acc) end, Defaults, Opts), Opts ++ maps:to_list(Rest) end. %%%=================================================================== %%% Mutable context processing %%%=================================================================== -spec get_ctx() -> ctx(). get_ctx() -> case get(yval_ctx) of undefined -> []; Opts -> Opts end. -spec put_ctx(ctx()) -> ok. put_ctx(Opts) -> put(yval_ctx, Opts), ok. -spec erase_ctx() -> ctx(). erase_ctx() -> case erase(yval_ctx) of Opts when is_list(Opts) -> lists:reverse(Opts); _ -> [] end. %%%=================================================================== %%% Copied from xmerl_regexp.erl to avoid xmerl dependency %%%=================================================================== -spec sh_to_awk(string()) -> string(). sh_to_awk(Sh) -> "^(" ++ sh_to_awk_1(Sh). %Fix the beginning sh_to_awk_1([$*|Sh]) -> %This matches any string ".*" ++ sh_to_awk_1(Sh); sh_to_awk_1([$?|Sh]) -> %This matches any character [$.|sh_to_awk_1(Sh)]; sh_to_awk_1([$[, $^, $]|Sh]) -> %This takes careful handling "\\^" ++ sh_to_awk_1(Sh); %% Must move '^' to end. sh_to_awk_1("[^" ++ Sh) -> [$[|sh_to_awk_2(Sh, true)]; sh_to_awk_1("[!" ++ Sh) -> "[^" ++ sh_to_awk_2(Sh, false); sh_to_awk_1([$[|Sh]) -> [$[|sh_to_awk_2(Sh, false)]; sh_to_awk_1([C|Sh]) -> %% Unspecialise everything else which is not an escape character. case sh_special_char(C) of true -> [$\\, C|sh_to_awk_1(Sh)]; false -> [C|sh_to_awk_1(Sh)] end; sh_to_awk_1([]) -> ")$". %Fix the end sh_to_awk_2([$]|Sh], UpArrow) -> [$]|sh_to_awk_3(Sh, UpArrow)]; sh_to_awk_2(Sh, UpArrow) -> sh_to_awk_3(Sh, UpArrow). sh_to_awk_3([$]|Sh], true) -> "^]" ++ sh_to_awk_1(Sh); sh_to_awk_3([$]|Sh], false) -> [$]|sh_to_awk_1(Sh)]; sh_to_awk_3([C|Sh], UpArrow) -> [C|sh_to_awk_3(Sh, UpArrow)]; sh_to_awk_3([], true) -> [$^|sh_to_awk_1([])]; sh_to_awk_3([], false) -> sh_to_awk_1([]). %% Test if a character is a special character. -spec sh_special_char(char()) -> boolean(). sh_special_char($|) -> true; sh_special_char($*) -> true; sh_special_char($+) -> true; sh_special_char($?) -> true; sh_special_char($() -> true; sh_special_char($)) -> true; sh_special_char($\\) -> true; sh_special_char($^) -> true; sh_special_char($$) -> true; sh_special_char($.) -> true; sh_special_char($[) -> true; sh_special_char($]) -> true; sh_special_char($") -> true; sh_special_char(_C) -> false. 07070100000007000041ED000000000000000000000002627E533500000000000000000000000000000000000000000000001100000000yval-1.0.10/test07070100000008000081A4000000000000000000000001627E533500005BFA000000000000000000000000000000000000001F00000000yval-1.0.10/test/yval_test.erl%%%------------------------------------------------------------------- %%% Created : 26 Sep 2018 by Evgeny Khramtsov <ekhramtsov@process-one.net> %%% %%% Copyright (C) 2002-2020 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -module(yval_test). %% API -import(yval, [validate/2]). -import(yval, [format_error/2]). %% Simple types -import(yval, [pos_int/0, pos_int/1, non_neg_int/0, non_neg_int/1]). -import(yval, [int/0, int/2, number/1, number/2, pos_number/0, octal/0]). -import(yval, [binary/0, binary/1, binary/2]). -import(yval, [string/0, string/1, string/2]). -import(yval, [enum/1, bool/0, atom/0, any/0]). %% Complex types -import(yval, [url/0, url/1]). -import(yval, [file/0, file/1]). -import(yval, [directory/0, directory/1]). -import(yval, [ip/0, ipv4/0, ipv6/0, ip_mask/0, port/0]). -import(yval, [re/0, re/1, glob/0, glob/1]). -import(yval, [path/0, binary_sep/1]). -import(yval, [beam/0, beam/1, base64/0]). -import(yval, [timeout/1, timeout/2]). -import(yval, [rfc3339_time/1]). -import(yval, [term/0, percent/0, percent/2]). %% Composite types -import(yval, [list/1, list/2]). -import(yval, [list_or_single/1, list_or_single/2]). -import(yval, [map/2, map/3]). -import(yval, [either/2, and_then/2, non_empty/1]). -import(yval, [options/1, options/2]). -include_lib("eunit/include/eunit.hrl"). -define(checkError(Pattern, Expression), (fun() -> ?assertError({yval, Pattern, _}, Expression) end)()). %%%=================================================================== %%% Tests %%%=================================================================== any_test() -> lists:foreach( fun(T) -> ?assertEqual(T, v(any(), T)) end, [1, [], <<"foo">>, 0.5, a, {}, fun() -> ok end, make_ref()]). error_validate_test() -> ?checkError({bad_int, _}, v(int(), foo)). enum_atom_test() -> ?assertEqual(foo, v(enum([foo, bar]), <<"foo">>)). enum_binary_test() -> ?assertEqual(<<"foo">>, v(enum([<<"foo">>, <<"bar">>]), <<"foo">>)). bad_enum_test() -> ?checkError({bad_enum, [foo, bar], baz}, (enum([foo, bar]))(<<"baz">>)). bool_test() -> ?assertEqual(true, v(bool(), <<"true">>)), ?assertEqual(true, v(bool(), <<"on">>)), ?assertEqual(true, v(bool(), <<"yes">>)), ?assertEqual(true, v(bool(), <<"y">>)), ?assertEqual(false, v(bool(), <<"false">>)), ?assertEqual(false, v(bool(), <<"off">>)), ?assertEqual(false, v(bool(), <<"no">>)), ?assertEqual(false, v(bool(), <<"n">>)). bad_bool_test() -> ?checkError({bad_bool, bad}, v(bool(), <<"bad">>)). int_test() -> ?assertEqual(5, v(int(), 5)), ?assertEqual(0, v(int(), 0)), ?assertEqual(-7, v(int(), -7)). bad_int_test() -> ?checkError({bad_int, _}, v(int(), <<"bad">>)). int_range_test() -> ?assertEqual(5, v(int(4, 5), 5)), ?assertEqual(0, v(int(-1, 5), 0)), ?assertEqual(-10, v(int(-10, 0), -10)). bad_int_range_test() -> ?checkError({bad_int, 10, 20, 5}, v(int(10, 20), 5)). pos_int_test() -> ?assertEqual(1, v(pos_int(), 1)). bad_pos_int_test() -> ?checkError({bad_pos_int, 0}, v(pos_int(), 0)). pos_int_infinity_test() -> ?assertEqual(1, v(pos_int(infinity), 1)), ?assertEqual(infinite, v(pos_int(infinite), infinity)), ?assertEqual(unlimited, v(pos_int(unlimited), infinite)), ?assertEqual(infinity, v(pos_int(infinity), unlimited)). bad_pos_int_infinity_test() -> ?checkError({bad_pos_int, infinity, 0}, v(pos_int(infinity), 0)), ?checkError({bad_int, foo}, v(pos_int(infinity), foo)), ?checkError({bad_int, _}, v(pos_int(infinity), list_to_binary(lists:duplicate(256, $z)))). non_neg_int_test() -> ?assertEqual(0, v(non_neg_int(), 0)). bad_non_neg_int_test() -> ?checkError({bad_non_neg_int, -1}, v(non_neg_int(), -1)). non_neg_int_infinity_test() -> ?assertEqual(0, v(non_neg_int(infinity), 0)), ?assertEqual(infinite, v(non_neg_int(infinite), infinity)), ?assertEqual(unlimited, v(non_neg_int(unlimited), infinite)), ?assertEqual(infinity, v(non_neg_int(infinity), unlimited)). bad_non_neg_int_infinity_test() -> ?checkError({bad_non_neg_int, infinity, -1}, v(non_neg_int(infinity), -1)). number_test() -> ?assertEqual(0.5, v(number(0.5), 0.5)). bad_number_test() -> ?checkError({bad_number, _}, v(number(1.0), <<"bad">>)), ?checkError({bad_number, 0.5, infinity, 0.4}, v(number(0.5), 0.4)). binary_test() -> ?assertEqual(<<"a">>, v(binary(), <<"a">>)), ?assertEqual(<<"a">>, v(binary(), a)). bad_binary_test() -> ?checkError({bad_binary, 1}, v(binary(), 1)). binary_re_test() -> ?assertEqual(<<"foo">>, v(binary("^[a-z]+$"), <<"foo">>)), ?assertEqual(<<"BAR">>, v(binary("^[A-Z]+$"), <<"BAR">>)), ?assertEqual(<<"123">>, v(binary("^[0-9]+$"), <<"123">>)). bad_binary_re_test() -> ?checkError( {nomatch, "^[a-z]+$", <<"fooBAR">>}, v(binary("^[a-z]+$"), <<"fooBAR">>)). base64_test() -> ?assertEqual(<<"foo">>, v(base64(), <<"Zm9v">>)). bad_base64_test() -> ?checkError({bad_base64, <<"foo">>}, v(base64(), <<"foo">>)). atom_test() -> ?assertEqual(atom, v(atom(), atom)), ?assertEqual(atom, v(atom(), <<"atom">>)). bad_atom_test() -> ?checkError({bad_atom, []}, v(atom(), [])). bad_atom_length_test() -> Bad = list_to_binary(lists:duplicate(256, $z)), ?checkError({bad_length, 255}, v(atom(), Bad)). string_test() -> ?assertEqual("foo", v(string(), <<"foo">>)). bad_string_test() -> ?checkError({bad_binary, []}, v(string(), [])). string_re_test() -> ?assertEqual("foo", v(string("^[a-z]+$"), <<"foo">>)), ?assertEqual("BAR", v(string("^[A-Z]+$"), <<"BAR">>)), ?assertEqual("123", v(string("^[0-9]+$"), <<"123">>)). bad_string_re_test() -> ?checkError( {nomatch, "^[a-z]+$", <<"fooBAR">>}, v(string("^[a-z]+$"), <<"fooBAR">>)). binary_sep_test() -> ?assertEqual( [<<"b">>, <<"c">>, <<"d">>], v(binary_sep("/"), <<"b/c//d//">>)). path_test() -> Path = filename:join([<<"/">>, <<"foo">>, <<"bar">>, <<"baz">>]), ?assertMatch(Path, v(path(), Path)). empty_path_test() -> ?checkError(empty_binary, v(path(), <<"">>)). file_read_test() -> File = file(""), File = file(["a: " ++ File]), ?assertMatch( [{a, _}], v(File, #{a => file()})). bad_file_read_test() -> File = file(["a: non_existent"]), ?checkError( {read_file, enoent, _}, v(File, #{a => file()})). file_write_test() -> File = file(""), File = file(["a: " ++ File]), ?assertMatch( [{a, _}], v(File, #{a => file(write)})). bad_file_write_test() -> File = file(["a: " ++ test_dir()]), ?checkError( {create_file, eisdir, _}, v(File, #{a => file(write)})), File = file(["a: " ++ filename:join(File, "foo")]), ?checkError( {create_dir, eexist, _}, v(File, #{a => file(write)})). directory_read_test() -> File = file(["a: " ++ test_dir()]), ?assertMatch( [{a, _}], v(File, #{a => directory()})). bad_directory_read_test() -> File = file(["a: non_existent"]), ?checkError( {read_dir, enoent, _}, v(File, #{a => directory()})). directory_write_test() -> File = file(["a: " ++ test_dir()]), ?assertMatch( [{a, _}], v(File, #{a => directory(write)})). bad_directory_write_test() -> File = file(""), File = file(["a: " ++ File]), ?checkError( {create_dir, eexist, _}, v(File, #{a => directory(write)})). url_test() -> ?assertEqual(<<"http://domain.tld">>, v(url(), <<"http://domain.tld">>)), ?assertEqual(<<"https://domain.tld">>, v(url(), <<"https://domain.tld">>)). url_any_test() -> ?assertEqual( <<"wss://domain.tld:8443">>, v(url([]), <<"wss://domain.tld:8443">>)). bad_url_scheme_test() -> ?checkError( {bad_url, {unsupported_scheme, <<"http">>}, <<"http://domain.tld">>}, v(url([https]), <<"http://domain.tld">>)). bad_url_host_test() -> ?checkError( {bad_url, empty_host, <<"http:///path">>}, v(url(), <<"http:///path">>)). bad_url_bad_port_test() -> ?checkError( {bad_url, bad_port, <<"http://domain.tld:0">>}, v(url(), <<"http://domain.tld:0">>)), ?checkError( {bad_url, bad_port, <<"http://domain.tld:65536">>}, v(url(), <<"http://domain.tld:65536">>)). bad_url_test() -> ?checkError({bad_url, _, <<":bad:">>}, v(url(), <<":bad:">>)). octal_test() -> File = file(["a: \"644\""]), ?assertEqual( [{a, 420}], v(File, #{a => octal()})). bad_octal_test() -> File = file(["a: \"9\""]), ?checkError( {bad_octal, <<"9">>}, v(File, #{a => octal()})). ipv4_test() -> File = file(["a: 127.0.0.1"]), ?assertEqual( [{a, {127,0,0,1}}], v(File, #{a => ipv4()})). bad_ipv4_test() -> File = file(["a: '::1'"]), ?checkError( {bad_ipv4, "::1"}, v(File, #{a => ipv4()})). ipv6_test() -> File = file(["a: '::1'"]), ?assertEqual( [{a, {0,0,0,0,0,0,0,1}}], v(File, #{a => ipv6()})). bad_ipv6_test() -> File = file(["a: 127.0.0.1"]), ?checkError( {bad_ipv6, "127.0.0.1"}, v(File, #{a => ipv6()})). ip_test() -> File = file(["a: 127.0.0.1", "b: '::1'"]), ?assertEqual( [{a, {127,0,0,1}}, {b, {0,0,0,0,0,0,0,1}}], v(File, #{a => ip(), b => ip()})). bad_ip_test() -> File = file(["a: bad"]), ?checkError( {bad_ip, "bad"}, v(File, #{a => ip()})). ip_mask_test() -> File = file(["a: 127.0.0.1", "b: 127.0.0.1/0", "c: 127.0.0.1/32", "d: '::1'", "e: '::1/0'", "f: '::1/128'"]), ?assertEqual( [{a, {{127,0,0,1}, 32}}, {b, {{127,0,0,1}, 0}}, {c, {{127,0,0,1}, 32}}, {d, {{0,0,0,0,0,0,0,1}, 128}}, {e, {{0,0,0,0,0,0,0,1}, 0}}, {f, {{0,0,0,0,0,0,0,1}, 128}}], v(File, #{a => ip_mask(), b => ip_mask(), c => ip_mask(), d => ip_mask(), e => ip_mask(), f => ip_mask()})). bad_ip_mask_test() -> File = file(["a: 127.0.0.1/128"]), ?checkError( {bad_ip_mask, "127.0.0.1/128"}, v(File, #{a => ip_mask()})). port_test() -> File = file(["a: 1", "b: 65535"]), ?assertEqual( [{a, 1}, {b, 65535}], v(File, #{a => port(), b => port()})). timeout_test() -> File = file(["millisecond: 1", "second: 1", "minute: 1", "hour: 1", "day: 1"]), ?assertEqual( [{millisecond, 1}, {second, 1000}, {minute, 60000}, {hour, 3600000}, {day, 86400000}], v(File, #{millisecond => timeout(millisecond), second => timeout(second), minute => timeout(minute), hour => timeout(hour), day => timeout(day)})). timeout_atom_test() -> ?assertEqual(5, v(timeout(millisecond), '5')). timeout_format_test() -> File = file(["ms: 1 ms", "msec: 1 msec", "msecs: 1 msecs", "millisec: 1 millisec", "millisecs: 1 millisecs", "millisecond: 1 millisecond", "s: 1 s", "sec: 1 sec", "secs: 1 secs", "second: 1 second", "seconds: 1 seconds", "m: 1 m", "min: 1 min", "mins: 1 mins", "minute: 1 minute", "minutes: 1 minutes", "h: 1 h", "hour: 1 hour", "hours: 1 hours", "d: 1 d", "day: 1 day", "days: 1 days"]), ?assertEqual( [{ms,1}, {msec,1}, {msecs,1}, {millisec,1}, {millisecs,1}, {millisecond,1}, {s,1000}, {sec,1000}, {secs,1000}, {second,1000}, {seconds,1000}, {m,60000}, {min,60000}, {mins,60000}, {minute,60000}, {minutes,60000}, {h,3600000}, {hour,3600000}, {hours,3600000}, {d,86400000}, {day,86400000}, {days,86400000}], v(File, #{'_' => timeout(millisecond)})). timeout_infinity_test() -> File = file(["a: infinity", "b: infinite", "c: unlimited"]), ?assertEqual( [{a, infinite}, {b, unlimited}, {c, infinity}], v(File, #{a => timeout(day, infinite), b => timeout(day, unlimited), c => timeout(day, infinity)})). bad_timeout_test() -> File = file(["a: []"]), ?checkError( {bad_timeout, []}, v(File, #{a => timeout(second)})), ?checkError( {bad_timeout, infinity, []}, v(File, #{a => timeout(second, infinity)})). bad_timeout_zero_test() -> File = file(["a: 0"]), ?checkError( {bad_pos_int, 0}, v(File, #{a => timeout(second)})), ?checkError( {bad_pos_int, infinity, 0}, v(File, #{a => timeout(second, infinity)})). bad_timeout_infinity_test() -> File = file(["a: foo"]), ?checkError( {bad_int, <<"foo">>}, v(File, #{a => timeout(second)})), ?checkError( {bad_enum, _, foo}, v(File, #{a => timeout(second, infinity)})). bad_timeout_unit_test() -> File = file(["a: 1foo"]), ?checkError( {bad_timeout_unit, "foo"}, v(File, #{a => timeout(second)})). bad_timeout_min_test() -> File = file(["a: 1ms"]), ?checkError( {bad_timeout_min, second}, v(File, #{a => timeout(second)})). bad_timeout_negative_test() -> File = file(["a: -1s"]), ?checkError( {bad_pos_int, -1}, v(File, #{a => timeout(second)})), ?checkError( {bad_pos_int, infinity, -1}, v(File, #{a => timeout(second, infinity)})). re_test() -> File = file(["a: ^[0-9]+$"]), ?assertMatch( [{a, _}], v(File, #{a => re()})). bad_re_test() -> File = file(["a: '['"]), ?checkError( {bad_regexp, {_, _}, _}, v(File, #{a => re()})). glob_test() -> File = file(["a: '*'"]), ?assertMatch( [{a, _}], v(File, #{a => glob()})). bad_glob_test() -> File = file(["a: '['"]), ?checkError( {bad_glob, {_, _}, _}, v(File, #{a => glob()})). beam_test() -> Exports = [[{foo, 1}, {parse, 2}], {parse, 3}, []], File = file(["a: yconf"]), ?assertMatch( [{a, yconf}], v(File, #{a => beam(Exports)})). bad_beam_test() -> File = file(["a: foo"]), ?checkError( {bad_module, foo}, v(File, #{a => beam()})), File = file(["a: yconf"]), ?checkError( {bad_export, {foo, 1}, yconf}, v(File, #{a => beam([[{foo, 1}, {bar, 2}]])})), ?checkError( {bad_export, {foo, 1}, yconf}, v(File, #{a => beam([{foo, 1}])})). non_empty_test() -> File = file(["a: [1,2,3]", "b: 1", "c: foo", "d: {e: f}"]), ?assertMatch( [{a, [1,2,3]}, {b, 1}, {c, foo}, {d, [_]}], v(File, #{a => non_empty(list(int())), b => non_empty(int()), c => non_empty(atom()), d => non_empty(map(any(), any()))})). empty_atom_test() -> File = file(["a: ''"]), ?checkError( empty_atom, v(File, #{a => non_empty(atom())})). empty_binary_test() -> File = file(["a: ''"]), ?checkError( empty_binary, v(File, #{a => non_empty(binary())})). empty_list_test() -> File = file(["a: []"]), ?checkError( empty_list, v(File, #{a => non_empty(list(any()))})). empty_map_test() -> File = file(["a: {}"]), ?checkError( empty_list, v(File, #{a => non_empty( map(any(), any()))})). list_test() -> File = file(["a: [1,2,3]"]), ?assertMatch( [{a, [1,2,3]}], v(File, #{a => list(any())})). bad_list_test() -> File = file(["a: 1"]), ?checkError( {bad_list, 1}, v(File, #{a => list(any())})). sorted_list_test() -> File = file(["a: [3,2,1]"]), ?assertMatch( [{a, [1,2,3]}], v(File, #{a => list(any(), [sorted])})). bad_sorted_list_test() -> File = file(["a: 1"]), ?checkError( {bad_list, 1}, v(File, #{a => list(any(), [sorted])})). unique_list_test() -> File = file(["a: [1,2,3]"]), ?assertMatch( [{a, [1,2,3]}], v(File, #{a => list(any(), [unique])})). bad_unique_list_test() -> File = file(["a: [1,2,1,3]"]), ?checkError( {duplicated_value, 1}, v(File, #{a => list(any(), [unique])})), File = file(["a: [foo, bar, foo]"]), ?checkError( {duplicated_value, foo}, v(File, #{a => list(atom(), [unique])})), File = file(["a: [[1], [2], [1]]"]), ?checkError( {duplicated_value, [1]}, v(File, #{a => list(any(), [unique])})). list_or_single_test() -> File = file(["a: 1", "b: [1,2,3]"]), ?assertMatch( [{a, [1]}, {b, [1,2,3]}], v(File, #{a => list_or_single(any()), b => list_or_single(any())})). sorted_list_or_single_test() -> File = file(["a: 1", "b: [3,2,1]"]), ?assertMatch( [{a, [1]}, {b, [1,2,3]}], v(File, #{a => list_or_single(any(), [sorted]), b => list_or_single(any(), [sorted])})). unique_list_or_single_test() -> File = file(["a: 1", "b: [1,2,3]"]), ?assertMatch( [{a, [1]}, {b, [1,2,3]}], v(File, #{a => list_or_single(any(), [unique]), b => list_or_single(any(), [unique])})). bad_unique_list_or_single_test() -> File = file(["a: 1", "b: [1,2,1,3]"]), ?checkError( {duplicated_value, 1}, v(File, #{a => list_or_single(any(), [unique]), b => list_or_single(any(), [unique])})). map_test() -> File = file(["a: {c: 2, b: 1}"]), ?assertEqual( [{a, [{c, 2}, {b, 1}]}], v(File, #{a => map(atom(), any())})), ?assertEqual( [{a, [{c, 2}, {b, 1}]}], v(File, #{a => map(atom(), any(), [unique])})), ?assertEqual( [{a, [{b, 1}, {c, 2}]}], v(File, #{a => map(atom(), any(), [{return, orddict}])})), ?assertEqual( [{a, #{b => 1, c => 2}}], v(File, #{a => map(atom(), any(), [{return, map}])})), Ret = v(File, #{a => map(atom(), any(), [{return, dict}])}), ?assertMatch([{a, _}], Ret), ?assertEqual( [{b, 1}, {c, 2}], lists:keysort(1, dict:to_list(element(2, hd(element(2, Ret)))))). bad_map_test() -> V = map(atom(), any()), File = file(["a: 1"]), ?checkError( {bad_map, 1}, v(File, #{a => V})), File = file(["a: [1,2,3]"]), ?checkError( {bad_map, [1,2,3]}, v(File, #{a => V})). bad_unique_map_test() -> File = file(["a: {c: 2, b: 1, c: 3}"]), ?checkError( {duplicated_key, c}, v(File, #{a => map(atom(), any(), [unique])})). either_test() -> V = either(bool(), int()), File = file(["a: true", "b: 5"]), ?assertEqual( [{a, true}, {b, 5}], v(File, #{a => V, b => V})). either_atom_test() -> V = either(atom, int()), File = file(["a: atom", "b: 1"]), ?assertEqual( [{a, atom}, {b, 1}], v(File, #{a => V, b => V})). and_then_test() -> V = and_then( list(int()), fun lists:sum/1), File = file(["a: [1,2,3]"]), ?assertEqual( [{a, 6}], v(File, #{a => V})). options_test() -> File = file(["a: {b: 1, c: true}"]), ?assertEqual( [{a, [{b, 1}, {c, true}]}], v(File, #{a => options( #{b => int(), c => bool(), d => atom()})})). options_return_map_test() -> ?assertEqual( #{a => 1, b => 2}, v(options(#{a => any(), b => any()}, [{return, map}]), [{<<"a">>, 1}, {<<"b">>, 2}])). options_return_dict_test() -> Ret = v(options(#{a => any(), b => any()}, [{return, dict}]), [{<<"a">>, 1}, {<<"b">>, 2}]), ?assertEqual( [{a, 1}, {b, 2}], lists:keysort(1, dict:to_list(element(2, Ret)))). options_return_orddict_test() -> ?assertEqual( [{a, 2}, {b, 1}], v(options(#{a => any(), b => any()}, [{return, orddict}]), [{<<"b">>, 1}, {<<"a">>, 2}])). options_default_validator_test() -> File = file(["a: {b: 1, c: true}"]), ?assertEqual( [{a, [{b, 1}, {c, true}]}], v(File, #{a => options( #{b => int(), '_' => bool()})})). bad_options_test() -> File = file(["a: 1"]), ?checkError( {bad_map, 1}, v(File, #{a => options(#{})})), File = file(["a: [1,2,3]"]), ?checkError( {bad_map, [1,2,3]}, v(File, #{a => options(#{})})). bad_binary_map_option_test() -> File = file(["a: {b: foo}"]), ?checkError( {bad_bool, foo}, v(File, #{a => map(binary(), bool())})). bad_integer_map_option_test() -> File = file(["a: {1: foo}"]), ?checkError( {bad_bool, foo}, v(File, #{a => map(int(), bool())})). unknown_option_test() -> ?checkError({unknown_option, [], a}, v(options(#{}), [{<<"a">>, 1}])). missing_option_test() -> ?checkError( {missing_option, b}, v(options(#{a => int(), b => any()}, [{required, [b]}]), [{<<"a">>, 1}])). disallowed_option_test() -> Y = [{<<"a">>, 1}, {<<"b">>, 2}], ?checkError( {disallowed_option, b}, v(options(#{a => int()}, [{disallowed, [b]}]), Y)), ?checkError( {disallowed_option, b}, v(options(#{a => int(), b => int()}, [{disallowed, [b]}]), Y)), ?checkError( {disallowed_option, b}, v(options(#{a => int(), b => int()}, [{required, [b]}, {disallowed, [b]}]), Y)). unknown_option_with_disallowed_test() -> ?checkError( {unknown_option, [a], c}, v(options(#{a => int(), b => int()}, [{disallowed, [b]}]), [{<<"a">>, 1}, {<<"c">>, 2}])). duplicated_option_test() -> Y = [{<<"a">>, 1}, {<<"b">>, 2}, {<<"a">>, 3}], ?checkError( {duplicated_option, a}, v(options(#{a => int(), b => int()}, [unique]), Y)), ?assertEqual( [{a, 1}, {b, 2}, {a, 3}], v(options(#{a => int(), b => int()}, []), Y)). duplicated_unspecified_option_test() -> ?checkError( {duplicated_option, b}, v(options(#{a => int(), '_' => any()}, [unique]), [{<<"a">>, 1}, {<<"b">>, 2}, {<<"b">>, 3}])). bad_cwd_test() -> test_format_error({error, {bad_cwd, eaccess}, []}). unknown_reason_test() -> test_format_error({error, foo, []}). unicode_test() -> UTF8CharList = [209, 134], UTF8CharBin = list_to_binary(UTF8CharList), UTF8CharAtom = list_to_atom(UTF8CharList), ?assertEqual( [{a, UTF8CharAtom}, {b, UTF8CharBin}], v(options(#{a => atom(), b => binary()}), [{<<"a">>, UTF8CharBin}, {<<"b">>, UTF8CharBin}])). %%%=================================================================== %%% Internal functions %%%=================================================================== test_dir() -> {ok, Cwd} = file:get_cwd(), filename:join(filename:dirname(Cwd), "test"). test_format_error({error, Why, Ctx}) -> ?assertMatch([_|_], format_error(Why, Ctx)). v(Fun, Arg) -> apply(Fun, [Arg]). 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!164 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor