yconf-1.0.12/0000755000232200023220000000000014075762024013266 5ustar debalancedebalanceyconf-1.0.12/README.md0000644000232200023220000000211614075762024014545 0ustar debalancedebalance# YAML configuration processor [![CI](https://github.com/processone/yconf/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/processone/yconf/actions/workflows/ci.yml) [![Coverage Status](https://coveralls.io/repos/processone/yconf/badge.svg?branch=master&service=github)](https://coveralls.io/github/processone/yconf?branch=master) [![Hex version](https://img.shields.io/hexpm/v/yconf.svg "Hex version")](https://hex.pm/packages/yconf) You can find usage example in ejabberd. See `econf.erl` and `ejabberd_options.erl` for most parts that are using it. Validation is performed based on rules that you pass to `yconf:parser/2`, there is no way to load those rules from some special syntax file. Generally you will do something like this: ``` yconf:parse("/home/me/conf.yml", #{ host => yconf:string(), opts => yconf:options(#{ addr => yconf:ip(), count => yconf:non_neg_int() } )}). ``` That when feed with: ``` host: "test.com" opts: addr: "127.0.0.1" count: 100 ``` should produce: ``` {ok,[{host,"test.com"},{opts,[{addr,{127,0,0,1}},{count,100}]}]} ``` yconf-1.0.12/rebar.config.script0000644000232200023220000001047114075762024017056 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : rebar.config.script %%% Author : Evgeniy Khramtsov %%% Purpose : Rebar build script. Compliant with rebar and rebar3. %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% Copyright (C) 2002-2021 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. %%% %%%---------------------------------------------------------------------- IsRebar3 = case application:get_key(rebar, vsn) of {ok, VSN} -> [VSN1 | _] = string:tokens(VSN, "-"), [Maj|_] = string:tokens(VSN1, "."), (list_to_integer(Maj) >= 3); undefined -> lists:keymember(mix, 1, application:loaded_applications()) end, JobId = case os:getenv("TRAVIS_JOB_ID") of false -> ""; V -> V end, ModCfg0 = fun(F, Cfg, [Key|Tail], Op, Default) -> {OldVal,PartCfg} = case lists:keytake(Key, 1, Cfg) of {value, {_, V1}, V2} -> {V1, V2}; false -> {if Tail == [] -> Default; true -> [] end, Cfg} end, case Tail of [] -> [{Key, Op(OldVal)} | PartCfg]; _ -> [{Key, F(F, OldVal, Tail, Op, Default)} | PartCfg] end end, ModCfg = fun(Cfg, Keys, Op, Default) -> ModCfg0(ModCfg0, Cfg, Keys, Op, Default) end, ModCfgS = fun(Cfg, Keys, Val) -> ModCfg0(ModCfg0, Cfg, Keys, fun(_V) -> Val end, "") end, FilterConfig = fun(F, Cfg, [{Path, true, ModFun, Default} | Tail]) -> F(F, ModCfg0(ModCfg0, Cfg, Path, ModFun, Default), Tail); (F, Cfg, [_ | Tail]) -> F(F, Cfg, Tail); (F, Cfg, []) -> Cfg end, AppendStr = fun(Append) -> fun("") -> Append; (Val) -> Val ++ " " ++ Append end end, AppendList = fun(Append) -> fun(Val) -> Val ++ Append end end, Rebar3DepsFilter = fun(DepsList) -> lists:map(fun({DepName,_, {git,_, {tag,Version}}}) -> {DepName, Version}; (Dep) -> Dep end, DepsList) end, GlobalDepsFilter = fun(Deps) -> DepNames = lists:map(fun({DepName, _, _}) -> DepName; ({DepName, _}) -> DepName end, Deps), lists:filtermap(fun(Dep) -> case code:lib_dir(Dep) of {error, _} -> {true,"Unable to locate dep '"++atom_to_list(Dep)++"' in system deps."}; _ -> false end end, DepNames) end, code:ensure_loaded(rand), RandUniform = erlang:function_exported(rand, uniform, 1), GithubConfig = case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of {"true", Token} when is_list(Token) -> CONFIG1 = [{coveralls_repo_token, Token}, {coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")}, {coveralls_commit_sha, os:getenv("GITHUB_SHA")}, {coveralls_service_number, os:getenv("GITHUB_RUN_NUMBER")}], case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request" andalso string:tokens(os:getenv("GITHUB_REF"), "/") of [_, "pull", PRNO, _] -> [{coveralls_service_pull_request, PRNO} | CONFIG1]; _ -> CONFIG1 end; _ -> [] end, Rules = [ {[deps], IsRebar3, Rebar3DepsFilter, []}, {[erl_opts], RandUniform, AppendList([{d, 'RAND_UNIFORM'}]), []}, {[plugins], os:getenv("COVERALLS") == "true", AppendList([{coveralls, {git, "https://github.com/processone/coveralls-erl.git", {branch, "addjsonfile"}}} ]), []}, {[deps], os:getenv("USE_GLOBAL_DEPS") /= false, GlobalDepsFilter, []} ], Config = FilterConfig(FilterConfig, CONFIG, Rules) ++ GithubConfig, %io:format("Rules:~n~p~n~nCONFIG:~n~p~n~nConfig:~n~p~n", [Rules, CONFIG, Config]), Config. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: yconf-1.0.12/CHANGELOG.md0000644000232200023220000000260114075762024015076 0ustar debalancedebalance# Version 1.0.12 * Updating fast_yaml to version 1.0.32. * Switch from using Travis to Github Actions as CI # Version 1.0.11 * Updating fast_yaml to version 1.0.31. * Fix unused variable warning * Update copyright year to 2021 * Export include_files/3 to fix several Dialyzer warnings # Version 1.0.10 * Updating fast_yaml to version 1.0.30. # Version 1.0.9 * Updating fast_yaml to version 1.0.29. # Version 1.0.8 * Updating fast_yaml to version 1.0.28. * Exclude old OTP releases from Travis # Version 1.0.7 * Updating fast_yaml to version 1.0.27. # Version 1.0.6 * Updating fast_yaml to version 1.0.26. * Updating fast_yaml to version 1.0.26. * Create README.md * Remove test cases useless since 3e042d17 * Fix Travis setup and test up to Erlang/OTP 22.3 * Many improvements in uri_parse/1 # Version 1.0.5 * Updating fast_yaml to version 1.0.25. # Version 1.0.4 * Updating fast_yaml to version 1.0.24. # Version 1.0.3 * Updating fast_yaml to version 1.0.23. * Update copyright year # Version 1.0.2 * Updating fast_yaml to version 1.0.22. * Correctly report directory name * Don't lowercase first letter in reason string * Update testing OTP releases * Convert to existing atom when validating bool or enum # Version 1.0.1 * Updating fast_yaml to version 1.0.21. * Improve handling of unicode values * Accept all boolean tokens allowed by yaml spec # Version 1.0.0 * Initial version yconf-1.0.12/Makefile0000644000232200023220000000407014075762024014727 0ustar debalancedebalanceREBAR ?= ./rebar IS_REBAR3:=$(shell expr `$(REBAR) --version | awk -F '[ .]' '/rebar / {print $$2}'` '>=' 3) all: src src: $(REBAR) get-deps $(REBAR) compile clean: $(REBAR) clean distclean: clean rm -f config.status rm -f config.log rm -rf autom4te.cache rm -rf _build rm -rf deps rm -rf ebin rm -f rebar.lock rm -f test/*.beam rm -rf priv rm -f vars.config rm -f erl_crash.dump rm -f compile_commands.json rm -rf dialyzer test: all $(REBAR) eunit xref: all $(REBAR) xref ifeq "$(IS_REBAR3)" "1" dialyzer: $(REBAR) dialyzer else deps := $(wildcard deps/*/ebin) dialyzer/erlang.plt: @mkdir -p dialyzer @dialyzer --build_plt --output_plt dialyzer/erlang.plt \ -o dialyzer/erlang.log --apps kernel stdlib erts inets; \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi dialyzer/deps.plt: @mkdir -p dialyzer @dialyzer --build_plt --output_plt dialyzer/deps.plt \ -o dialyzer/deps.log $(deps); \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi dialyzer/yconf.plt: @mkdir -p dialyzer @dialyzer --build_plt --output_plt dialyzer/yconf.plt \ -o dialyzer/yconf.log ebin; \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi erlang_plt: dialyzer/erlang.plt @dialyzer --plt dialyzer/erlang.plt --check_plt -o dialyzer/erlang.log; \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi deps_plt: dialyzer/deps.plt @dialyzer --plt dialyzer/deps.plt --check_plt -o dialyzer/deps.log; \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi yconf_plt: dialyzer/yconf.plt @dialyzer --plt dialyzer/yconf.plt --check_plt -o dialyzer/yconf.log; \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi dialyzer: erlang_plt deps_plt yconf_plt @dialyzer --plts dialyzer/*.plt --no_check_plt \ --get_warnings -Wunmatched_returns -o dialyzer/error.log ebin; \ status=$$? ; if [ $$status -ne 2 ]; then exit $$status; else exit 0; fi endif check-syntax: gcc -o nul -S ${CHK_SOURCES} .PHONY: clean src test all dialyzer erlang_plt deps_plt yconf_plt yconf-1.0.12/src/0000755000232200023220000000000014075762024014055 5ustar debalancedebalanceyconf-1.0.12/src/yconf.erl0000644000232200023220000011640214075762024015703 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% @copyright (C) 2002-2021 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(yconf). %% API -export([start/0, stop/0]). -export([parse/2, parse/3, validate/2, fail/2, replace_macros/1]). -export([format_error/1, format_error/2, format_ctx/1, include_files/3]). %% Simple types -export([pos_int/0, pos_int/1, non_neg_int/0, non_neg_int/1]). -export([int/0, int/2, number/1, 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([timeout/1, timeout/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)). -ifndef(deprecated_stacktrace). -define(EX_RULE(Class, Reason, Stack), Class:Reason:Stack). -define(EX_STACK(Stack), Stack). -else. -define(EX_RULE(Class, Reason, _), Class:Reason). -define(EX_STACK(_), erlang:get_stacktrace()). -endif. -type infinity() :: infinity | infinite | unlimited. -type timeout_unit() :: millisecond | second | minute | hour | day. -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 macro() :: {binary(), yaml()}. -type includes() :: [{binary(), {[atom()], [atom()]}} | binary()]. -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 parse_option() :: replace_macros | {replace_macros, boolean()} | include_files | {include_files, boolean()} | plain_as_atom | {plain_as_atom, boolean()}. -type validator_option() :: {required, [atom()]} | {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]). -export_type([error_return/0, error_reason/0, ctx/0]). %%%=================================================================== %%% API %%%=================================================================== start() -> case application:ensure_all_started(?MODULE) of {ok, _} -> ok; Err -> Err end. stop() -> ok. -spec parse(file:filename_all(), validator() | validators()) -> {ok, options()} | error_return(). parse(Path, Validators) -> parse(Path, Validators, [unique]). -spec parse(file:filename_all(), validator() | validators(), [parse_option() | validator_option()]) -> {ok, options()} | error_return(). parse(Path0, Validators, Opts) -> Path = unicode:characters_to_binary(Path0), {Opts1, Opts2} = proplists:split( proplists:compact(Opts), [replace_macros, include_files, plain_as_atom]), Opts3 = lists:flatten(Opts1), try Y1 = read_yaml(prep_path(Path), Opts3, []), Y2 = replace_macros(Y1, Opts3), Validators1 = maps:merge(Validators, validators(Opts3)), {ok, (options(Validators1, Opts2))(Y2)} catch _:{?MODULE, Why, Ctx} -> {error, Why, Ctx}; ?EX_RULE(Class, Reason, Stacktrace) -> _ = erase_ctx(), erlang:raise(Class, Reason, ?EX_STACK(Stacktrace)) end. -spec validate(validator(), yaml()) -> {ok, any()} | error_return(). validate(Validator, Y) -> try {ok, Validator(Y)} catch _:{?MODULE, Why, Ctx} -> {error, Why, Ctx}; ?EX_RULE(Class, Reason, Stacktrace) -> _ = erase_ctx(), erlang:raise(Class, Reason, ?EX_STACK(Stacktrace)) end. -spec replace_macros(yaml_map()) -> {ok, yaml_map()} | error_return(). replace_macros(Y) -> try {ok, replace_macros(Y, [replace_macros])} catch _:{?MODULE, Why, Ctx} -> {error, Why, Ctx}; ?EX_RULE(Class, Reason, Stacktrace) -> _ = erase_ctx(), erlang:raise(Class, Reason, ?EX_STACK(Stacktrace)) end. -spec fail(term(), term()) -> no_return(). fail(Tag, Reason) -> erlang:nif_error({Tag, Reason, erase_ctx()}). %%%=================================================================== %%% 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()) -> validator(integer()). int(Min, Max) when is_integer(Min), is_integer(Max), Min =< Max -> fun(Val) -> case to_int(Val) of I when I>=Min, I= I; Bad -> fail({bad_int, Min, Max, Bad}) end end. -spec number(number()) -> validator(number()). number(Min) -> fun(Val) -> case to_number(Val) of N when N >= Min -> N; Bad -> fail({bad_number, Min, Bad}) end end. -spec binary() -> validator(binary()). binary() -> fun to_binary/1. -spec binary(iodata()) -> validator(binary()). binary(Regexp) -> binary(Regexp, []). -spec binary(iodata(), [re:compile_option()]) -> validator(binary()). binary(Regexp, Opts) when is_list(Regexp) orelse is_binary(Regexp) -> fun(Val) -> Bin = to_binary(Val), case re:run(Bin, Regexp, Opts) of {match, _} -> Bin; nomatch -> fail({nomatch, Regexp, Bin}) 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, []). -spec string(iodata(), [re:compile_option()]) -> validator(string()). string(Regexp, Opts) when is_list(Regexp) orelse is_binary(Regexp) -> fun(Val) -> Str = to_string(Val), case re:run(Str, Regexp, Opts) of {match, _} -> Str; nomatch -> fail({nomatch, Regexp, Str}) 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(Schemes) -> fun(Val) -> URL = to_binary(Val), case parse_uri(URL) of {ok, _, Host, _} when Host == ""; Host == <<"">> -> fail({bad_url, empty_host, URL}); {ok, _, _, Port} when Port /= undefined, Port =< 0 orelse Port >= 65536 -> fail({bad_url, bad_port, URL}); {ok, Scheme, _, _} when Schemes /= [] -> case lists:member(Scheme, Schemes) of true -> URL; false -> fail({bad_url, {unsupported_scheme, Scheme}, URL}) end; {ok, _, _, _} -> URL; {error, Why} -> 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 re() -> validator(re:mp()). re() -> re([]). -spec re([re:compile_option()]) -> validator(re:mp()). 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(re:mp()). glob() -> glob([]). -spec glob([re:compile_option()]) -> validator(re:mp()). 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 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, []), 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, 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_bool, Bad}) -> format("Expected boolean, got ~s instead", [format_yaml_type(Bad)]); format_error({bad_base64, _}) -> format("Invalid Base64 string", []); format_error({bad_cwd, Why}) -> format("Failed to get current directory name: ~s", [file:format_error(Why)]); format_error({bad_enum, _, Val}) -> format("Unexpected value: ~s", [Val]); 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, 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, Bad}) -> format("Expected number >= ~p, got: ~p", [Min, 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_url, empty_host, URL}) -> format("Empty hostname 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, {no_default_port, _, _}, URL}) -> format("Missing port in the URL: ~s", [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_yaml, circular_include, Path}) -> format("Circularly included YAML file: ~s", [Path]); format_error({circular_macro, Name}) -> format("Circularly defined macro: ~s", [Name]); format_error({bad_yaml, Why, Path}) -> format("Failed to read YAML file '~s': ~s", [Path, fast_yaml:format_error(Why)]); 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("Option '~s' is not allowed in this context", [Opt]); format_error({duplicated_key, Key}) -> format("Duplicated key: ~s", [Key]); format_error({duplicated_value, Val}) -> format("Duplicated value: ~s", [format_yaml(Val)]); format_error({duplicated_option, Opt}) -> format("Duplicated option: ~s", [Opt]); format_error({duplicated_macro, Name}) -> format("Duplicated macro: ~s", [Name]); 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({missing_option, Opt}) -> format("Missing required option: ~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, _, Opt}) -> format("Unknown option: ~s", [Opt]); format_error(Unexpected) -> format("Unexpected error reason: ~p", [Unexpected]). -spec format_ctx(ctx()) -> string(). format_ctx([]) -> "Configuration error"; format_ctx([_|_] = Ctx) -> format("Invalid value of option ~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(fast_yaml:encode(Y)) catch _:_ -> try iolist_to_binary(Y) catch _:_ -> list_to_binary(io_lib:format("~p", [Y])) end end, case binary:match(S, <<"\n">>) of nomatch -> S; _ -> [io_lib:nl(), S] end. %%%=================================================================== %%% Internal functions %%%=================================================================== %%%=================================================================== %%% Initial YAML parsing %%%=================================================================== -spec read_yaml(binary(), [parse_option()], [binary()]) -> yaml_map(). read_yaml(Path, Opts, Paths) -> case lists:member(Path, Paths) of true -> fail({bad_yaml, circular_include, Path}); false -> PlainAsAtom = proplists:get_bool(plain_as_atom, Opts), IncludeFiles = proplists:get_bool(include_files, Opts), case fast_yaml:decode_from_file( Path, [{plain_as_atom, PlainAsAtom}]) of {ok, [Y]} when IncludeFiles -> Validators = validators([include_files]), V = and_then( options(Validators#{'_' => any()}, []), fun(Y1) -> include_files(Y1, Opts, [Path|Paths]) end), V(Y); {ok, [Y]} -> Y; {ok, []} -> []; {error, Why} -> fail({bad_yaml, Why, Path}) end end. -spec partition_macros(options()) -> {[macro()], yaml_map()}. partition_macros(Opts) -> lists:foldr( fun({define_macro, M}, {Ms, Os}) -> {M ++ Ms, Os}; (O, {Ms, Os}) -> {Ms, [O|Os]} end, {[], []}, Opts). -spec replace_macros(yaml_map(), [parse_option()]) -> yaml_map(). replace_macros(Y, Opts) -> case proplists:get_bool(replace_macros, Opts) of true -> Validators = validators([replace_macros]), V = and_then( options(Validators#{'_' => any()}, []), fun(Y1) -> {Macros1, Y2} = partition_macros(Y1), Macros2 = check_duplicated_macros(Macros1), Macros3 = replace_macros(Macros2, Macros2, []), replace_macros(Y2, Macros3, []) end), V(Y); false -> Y end. -spec check_duplicated_macros([macro()]) -> [macro()]. check_duplicated_macros(Macros) -> lists:foldl( fun({Name, Val}, Ms) -> case lists:keymember(Name, 1, Ms) of true -> fail({duplicated_macro, Name}); false -> [{Name, Val}|Ms] end end, [], Macros). -spec replace_macros(yaml_map(), [macro()], [binary()]) -> yaml_map(). replace_macros(Y, Macros, Path) -> lists:foldr( fun(Macro, Y1) -> replace_macro(Y1, Macro, Macros, Path) end, Y, Macros). -spec replace_macro(yaml(), macro(), [macro()], [binary()]) -> yaml(). replace_macro(L, Macro, Macros, Path) when is_list(L) -> [replace_macro(E, Macro, Macros, Path) || E <- L]; replace_macro({K, V}, Macro, Macros, Path) -> {K, replace_macro(V, Macro, Macros, Path)}; replace_macro(V, {Name, Val}, Macros, Path) -> V1 = if is_atom(V) -> atom_to_binary(V, latin1); true -> V end, case V1 of Name -> case lists:member(Name, Path) of true -> fail({circular_macro, Name}); false -> replace_macros(Val, Macros, [Name|Path]) end; _ -> V end; replace_macro(Val, _, _, _) -> Val. -spec include_files(options(), [parse_option()], [binary()]) -> yaml_map(). include_files(List, Opts, Paths) -> lists:flatmap( fun({include_config_file, Includes}) -> read_include_files(Includes, Opts, Paths); (Y) -> [Y] end, List). -spec read_include_files(includes(), [parse_option()], [binary()]) -> yaml_map(). read_include_files(Includes, Opts, Paths) -> lists:flatmap( fun({File, {Disallow, AllowOnly}}) -> Y = read_yaml(File, Opts, Paths), lists:filter( fun({Opt, _}) -> case AllowOnly of [] -> not lists:member(Opt, Disallow); _ -> lists:member(Opt, AllowOnly) end end, Y); (File) -> read_yaml(File, Opts, Paths) end, Includes). %%%=================================================================== %%% 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 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 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 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 parse_uri(term()) -> {ok, atom(), binary(), integer() | undefined} | {error, term()}. -ifdef(USE_OLD_HTTP_URI). parse_uri(URL) when is_binary(URL) -> parse_uri(to_string(URL)); % OTP =< 19's http_uri:parse/1 expects strings. parse_uri(URL) -> case http_uri:parse(URL) of {ok, {Scheme, _UserInfo, Host, Port0, _Path, _Query}} -> Port = if is_integer(Port0) -> Port0; true -> undefined end, {ok, Scheme, Host, Port}; {error, Reason} -> {error, Reason} end. -else. parse_uri(URL0) -> URL = re:replace(URL0, <<"@[A-Z]+@">>, <<"MACRO">>, [{return, binary}]), case uri_string:parse(URL) of URIMap when is_map(URIMap) -> Scheme = maps:get(scheme, URIMap, <<>>), Host = maps:get(host, URIMap, <<>>), Port = maps:get(port, URIMap, undefined), {ok, to_atom(Scheme), Host, Port}; {error, Reason, _Info} -> {error, Reason} end. -endif. -spec fail(error_reason()) -> no_return(). fail(Reason) -> fail(?MODULE, Reason). -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()], boolean(), return_type()) -> options(). validate_options(Opts, Validators, DefaultValidator, Required, Disallowed, CheckDups, Return) -> validate_options(Opts, Validators, DefaultValidator, Required, Disallowed, CheckDups, Return, []). -spec validate_options(list(), validators(), validator() | undefined, [atom()], [atom()], boolean(), return_type(), options()) -> options(). validate_options([{O, Val}|Opts], Validators, DefaultValidator, Required, Disallowed, CheckDups, Return, Acc) -> Opt = to_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 -> 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, Disallowed, CheckDups, Return, Acc1) end end end; validate_options([], _, _, [], _, _, Return, Acc) -> case Return of list -> lists:reverse(Acc); map -> maps:from_list(Acc); dict -> dict:from_list(Acc); orddict -> orddict:from_list(Acc) 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. %%%=================================================================== %%% Mutable context processing %%%=================================================================== -spec get_ctx() -> ctx(). get_ctx() -> case get(yconf_ctx) of undefined -> []; Opts -> Opts end. -spec put_ctx(ctx()) -> ok. put_ctx(Opts) -> put(yconf_ctx, Opts), ok. -spec erase_ctx() -> ctx(). erase_ctx() -> case erase(yconf_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. %%%=================================================================== %%% Bootstrapping validator %%%=================================================================== -spec validators([parse_option()]) -> validators(). validators(Opts) when is_list(Opts) -> lists:foldl( fun(replace_macros, V) -> maps:put(define_macro, validator(define_macro), V); (include_files, V) -> maps:put(include_config_file, validator(include_config_file), V); (_, V) -> V end, #{}, Opts). validator(define_macro) -> map(binary("^[A-Z_0-9]+$"), any()); validator(include_config_file) -> either( list_or_single(path()), map(path(), and_then( options( #{disallow => list(atom()), allow_only => list(atom())}), fun(Opts) -> {proplists:get_value(disallow, Opts, []), proplists:get_value(allow_only, Opts, [])} end))). yconf-1.0.12/src/yconf.app.src0000644000232200023220000000235314075762024016466 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% @copyright (C) 2002-2021 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. %%% %%%------------------------------------------------------------------- {application, yconf, [{description, "YAML configuration processor"}, {vsn, "1.0.12"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib, fast_yaml]}, {env, []}, %% hex.pm packaging: {licenses, ["Apache 2.0"]}, {links, [{"Github", "https://github.com/processone/yconf"}]} ]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: yconf-1.0.12/rebar.config0000644000232200023220000000271314075762024015553 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% @copyright (C) 2002-2021 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. %%% %%%------------------------------------------------------------------- {erl_opts, [debug_info, {src_dirs, ["src"]}, {i, "include"}, {platform_define, "^(R|1|20)", 'USE_OLD_HTTP_URI'}, {platform_define, "^(R|1|20)", deprecated_stacktrace}]}. {deps, [{fast_yaml, ".*", {git, "https://github.com/processone/fast_yaml", {tag, "1.0.32"}}}]}. {cover_enabled, true}. {cover_export_enabled, true}. {coveralls_coverdata , "_build/test/cover/eunit.coverdata"}. {coveralls_service_name , "github"}. {xref_checks, [undefined_function_calls, undefined_functions, deprecated_function_calls, deprecated_functions]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: yconf-1.0.12/test/0000755000232200023220000000000014075762024014245 5ustar debalancedebalanceyconf-1.0.12/test/yconf_test.erl0000644000232200023220000007462014075762024017137 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% Created : 26 Sep 2018 by Evgeny Khramtsov %%% %%% Copyright (C) 2002-2021 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(yconf_test). -include_lib("eunit/include/eunit.hrl"). -define(checkError(Pattern, Expression), (fun() -> Ret = Expression, ?assertMatch({error, Pattern, _}, Ret), test_format_error(Ret) end)()). %%%=================================================================== %%% Tests %%%=================================================================== start_test() -> ?assertEqual(ok, yconf:start()). validate_test() -> ?assertEqual({ok, 1}, yconf:validate(yconf:any(), 1)). error_validate_test() -> ?checkError( {bad_int, _}, yconf:validate(yconf:int(), foo)). empty_yaml_test() -> File = file(""), ?assertEqual({ok, []}, yconf:parse(File, #{})). bad_yaml_test() -> ?checkError( {bad_yaml, enoent, _}, yconf:parse("non-existent.yml", #{})). define_macro_test() -> File = file(["define_macro:", " A: 1", " B: 2", " C: 3", "a: A", "b: B", "c: C"]), ?assertEqual( {ok, [{a, 1}, {b, 2}, {c, 3}]}, yconf:parse(File, #{'_' => yconf:any()}, [replace_macros])). include_config_file_test() -> IncludedFile = included_file(["a: 1", "b: 2"]), File = file(["include_config_file: " ++ IncludedFile, "c: 3"]), ?assertEqual( {ok, [{a, 1}, {b, 2}, {c, 3}]}, yconf:parse(File, #{'_' => yconf:any()}, [include_files])). include_allow_only_test() -> IncludedFile = included_file(["a: 1", "b: 2", "c: 3"]), File = file(["include_config_file:", " " ++ IncludedFile ++ ":", " allow_only:", " - a", " - c"]), ?assertEqual( {ok, [{a, 1}, {c, 3}]}, yconf:parse(File, #{'_' => yconf:any()}, [include_files])). include_disallow_test() -> IncludedFile = included_file(["a: 1", "b: 2", "c: 3"]), File = file(["include_config_file:", " " ++ IncludedFile ++ ":", " disallow:", " - a", " - c"]), ?assertEqual( {ok, [{b, 2}]}, yconf:parse(File, #{'_' => yconf:any()}, [include_files])). duplicated_macro_test() -> File = file(["define_macro:", " MACRO: 1", "define_macro:", " MACRO: 2", "a: MACRO"]), ?checkError( {duplicated_macro, <<"MACRO">>}, yconf:parse(File, #{'_' => yconf:any()}, [replace_macros])). included_macro_test() -> IncludedFile = included_file(["define_macro:", " MACRO: 1", "b: MACRO"]), File = file(["a: MACRO", "include_config_file: " ++ IncludedFile]), ?assertEqual( {ok, [{a, 1}, {b, 1}]}, yconf:parse(File, #{'_' => yconf:any()}, [replace_macros, include_files])). nested_macro_test() -> File = file(["define_macro:", " FOO: BAR", " BAR: BAZ", " BAZ: baz", "foo: FOO", "bar: FOO", "baz: FOO"]), ?assertEqual( {ok, [{foo, <<"baz">>}, {bar, <<"baz">>}, {baz, <<"baz">>}]}, yconf:parse(File, #{'_' => yconf:any()}, [replace_macros])). include_circular_test() -> File = file(""), IncludedFile = included_file(["include_config_file: " ++ File]), File = file(["include_config_file: " ++ IncludedFile]), ?checkError( {bad_yaml, circular_include, _}, yconf:parse(File, #{}, [include_files])). macro_circular_test() -> File = file(["define_macro:", " FOO: BAR", " BAR: BAZ", " BAZ: FOO"]), ?checkError( {circular_macro, <<"FOO">>}, yconf:parse(File, #{}, [replace_macros])). any_test() -> File = file(["a: 1"]), ?assertEqual( {ok, [{a, 1}]}, yconf:parse(File, #{a => yconf:any()})). enum_atom_test() -> File = file(["a: foo"]), ?assertEqual( {ok, [{a, foo}]}, yconf:parse(File, #{a => yconf:enum([foo, bar])})). enum_binary_test() -> File = file(["a: foo"]), ?assertEqual( {ok, [{a, <<"foo">>}]}, yconf:parse(File, #{a => yconf:enum([<<"foo">>, <<"bar">>])})). bad_enum_test() -> File = file(["a: baz"]), ?checkError( {bad_enum, [foo, bar], baz}, yconf:parse(File, #{a => yconf:enum([foo, bar])})). bool_test() -> File = file(["a: true", "b: false", "c: on", "d: off", "e: yes", "f: no", "g: y", "h: n"]), ?assertEqual( {ok, [{a, true}, {b, false}, {c, true}, {d, false}, {e, true}, {f, false}, {g, true}, {h, false}]}, yconf:parse(File, #{a => yconf:bool(), b => yconf:bool(), c => yconf:bool(), d => yconf:bool(), e => yconf:bool(), f => yconf:bool(), g => yconf:bool(), h => yconf:bool()})). bad_bool_test() -> File = file(["a: bad"]), ?checkError( {bad_bool, bad}, yconf:parse(File, #{a => yconf:bool()})). int_test() -> File = file(["a: 5", "b: 0", "c: -7"]), ?assertEqual( {ok, [{a, 5}, {b, 0}, {c, -7}]}, yconf:parse(File, #{a => yconf:int(), b => yconf:int(), c => yconf:int()})). bad_int_test() -> File = file(["a: bad"]), ?checkError( {bad_int, _}, yconf:parse(File, #{a => yconf:int()})). int_range_test() -> File = file(["a: 5", "b: 0", "c: -10"]), ?assertEqual( {ok, [{a, 5}, {b, 0}, {c, -10}]}, yconf:parse(File, #{a => yconf:int(4, 5), b => yconf:int(-1, 5), c => yconf:int(-10, 0)})). bad_int_range_test() -> File = file(["a: 5"]), ?checkError( {bad_int, 10, 20, 5}, yconf:parse(File, #{a => yconf:int(10, 20)})). pos_int_test() -> File = file(["a: 1"]), ?assertEqual( {ok, [{a, 1}]}, yconf:parse(File, #{a => yconf:pos_int()})). bad_pos_int_test() -> File = file(["a: 0"]), ?checkError( {bad_pos_int, 0}, yconf:parse(File, #{a => yconf:pos_int()})). pos_int_infinity_test() -> File = file(["a: 1", "b: infinity", "c: infinite", "d: unlimited"]), ?assertEqual( {ok, [{a, 1}, {b, infinite}, {c, unlimited}, {d, infinity}]}, yconf:parse(File, #{a => yconf:pos_int(infinity), b => yconf:pos_int(infinite), c => yconf:pos_int(unlimited), d => yconf:pos_int(infinity)})). bad_pos_int_infinity_test() -> File = file(["a: 0"]), ?checkError( {bad_pos_int, infinity, 0}, yconf:parse(File, #{a => yconf:pos_int(infinity)})), ?checkError( {bad_int, foo}, yconf:validate(yconf:pos_int(infinity), foo)), ?checkError( {bad_int, _}, yconf:validate( yconf:pos_int(infinity), list_to_binary(lists:duplicate(256, $z)))). non_neg_int_test() -> File = file(["a: 0"]), ?assertEqual( {ok, [{a, 0}]}, yconf:parse(File, #{a => yconf:non_neg_int()})). bad_non_neg_int_test() -> File = file(["a: -1"]), ?checkError( {bad_non_neg_int, -1}, yconf:parse(File, #{a => yconf:non_neg_int()})). non_neg_int_infinity_test() -> File = file(["a: 0", "b: infinity", "c: infinite", "d: unlimited"]), ?assertEqual( {ok, [{a, 0}, {b, infinite}, {c, unlimited}, {d, infinity}]}, yconf:parse(File, #{a => yconf:non_neg_int(infinity), b => yconf:non_neg_int(infinite), c => yconf:non_neg_int(unlimited), d => yconf:non_neg_int(infinity)})). bad_non_neg_int_infinity_test() -> File = file(["a: -1"]), ?checkError( {bad_non_neg_int, infinity, -1}, yconf:parse(File, #{a => yconf:non_neg_int(infinity)})). number_test() -> File = file(["a: 0.5"]), ?assertEqual( {ok, [{a, 0.5}]}, yconf:parse(File, #{a => yconf:number(0.5)})). bad_number_test() -> File = file(["a: bad"]), ?checkError( {bad_number, _}, yconf:parse(File, #{a => yconf:number(1.0)})), File = file(["a: 0.4"]), ?checkError( {bad_number, 0.5, 0.4}, yconf:parse(File, #{a => yconf:number(0.5)})). binary_test() -> File = file(["a: foo", "b: \"bar\"", "c: 'baz'"]), ?assertEqual( {ok, [{a, <<"foo">>}, {b, <<"bar">>}, {c, <<"baz">>}]}, yconf:parse(File, #{a => yconf:binary(), b => yconf:binary(), c => yconf:binary()})), ?assertEqual(<<"foo">>, (yconf:binary())(foo)). bad_binary_test() -> File = file(["a: 1"]), ?checkError( {bad_binary, 1}, yconf:parse(File, #{a => yconf:binary()})). binary_re_test() -> File = file(["a: foo", "b: BAR", "c: \"123\""]), ?assertEqual( {ok, [{a, <<"foo">>}, {b, <<"BAR">>}, {c, <<"123">>}]}, yconf:parse(File, #{a => yconf:binary("^[a-z]+$"), b => yconf:binary("^[A-Z]+$"), c => yconf:binary("^[0-9]+$")})). bad_binary_re_test() -> File = file(["a: fooBAR"]), ?checkError( {nomatch, "^[a-z]+$", <<"fooBAR">>}, yconf:parse(File, #{a => yconf:binary("^[a-z]+$")})). base64_test() -> File = file(["a: Zm9v"]), ?assertEqual( {ok, [{a, <<"foo">>}]}, yconf:parse(File, #{a => yconf:base64()})). bad_base64_test() -> File = file(["a: foo"]), ?checkError( {bad_base64, <<"foo">>}, yconf:parse(File, #{a => yconf:base64()})). atom_test() -> File = file(["a: atom"]), ?assertEqual( {ok, [{a, atom}]}, yconf:parse(File, #{a => yconf:atom()})). bad_atom_test() -> File = file(["a: []"]), ?checkError( {bad_atom, []}, yconf:parse(File, #{a => yconf:atom()})). bad_atom_length_test() -> Bad = list_to_binary(lists:duplicate(256, $z)), ?checkError( {bad_length, 255}, yconf:validate(yconf:atom(), Bad)). string_test() -> File = file(["a: foo"]), ?assertEqual( {ok, [{a, "foo"}]}, yconf:parse(File, #{a => yconf:string()})). bad_string_test() -> File = file(["a: []"]), ?checkError( {bad_binary, []}, yconf:parse(File, #{a => yconf:string()})). string_re_test() -> File = file(["a: foo", "b: BAR", "c: \"123\""]), ?assertEqual( {ok, [{a, "foo"}, {b, "BAR"}, {c, "123"}]}, yconf:parse(File, #{a => yconf:string("^[a-z]+$"), b => yconf:string("^[A-Z]+$"), c => yconf:string("^[0-9]+$")})). bad_string_re_test() -> File = file(["a: fooBAR"]), ?checkError( {nomatch, "^[a-z]+$", "fooBAR"}, yconf:parse(File, #{a => yconf:string("^[a-z]+$")})). binary_sep_test() -> File = file(["a: b/c//d//"]), ?assertEqual( {ok, [{a, [<<"b">>, <<"c">>, <<"d">>]}]}, yconf:parse(File, #{a => yconf:binary_sep("/")})). path_test() -> File = file(["a: foo"]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:path()})). empty_path_test() -> File = file(["a: ''"]), ?checkError( empty_binary, yconf:parse(File, #{a => yconf:path()})). file_read_test() -> File = file(""), File = file(["a: " ++ File]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:file()})). bad_file_read_test() -> File = file(["a: non_existent"]), ?checkError( {read_file, enoent, _}, yconf:parse(File, #{a => yconf:file()})). file_write_test() -> File = file(""), File = file(["a: " ++ File]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:file(write)})). bad_file_write_test() -> File = file(["a: " ++ test_dir()]), ?checkError( {create_file, eisdir, _}, yconf:parse(File, #{a => yconf:file(write)})), File = file(["a: " ++ filename:join(File, "foo")]), ?checkError( {create_dir, eexist, _}, yconf:parse(File, #{a => yconf:file(write)})). directory_read_test() -> File = file(["a: " ++ test_dir()]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:directory()})). bad_directory_read_test() -> File = file(["a: non_existent"]), ?checkError( {read_dir, enoent, _}, yconf:parse(File, #{a => yconf:directory()})). directory_write_test() -> File = file(["a: " ++ test_dir()]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:directory(write)})). bad_directory_write_test() -> File = file(""), File = file(["a: " ++ File]), ?checkError( {create_dir, eexist, _}, yconf:parse(File, #{a => yconf:directory(write)})). url_test() -> File = file(["a: http://domain.tld", "b: https://domain.tld"]), ?assertEqual( {ok, [{a, <<"http://domain.tld">>}, {b, <<"https://domain.tld">>}]}, yconf:parse(File, #{a => yconf:url(), b => yconf:url()})). url_any_test() -> File = file(["a: wss://domain.tld:8443"]), ?assertEqual( {ok, [{a, <<"wss://domain.tld:8443">>}]}, yconf:parse(File, #{a => yconf:url([])})). bad_url_scheme_test() -> File = file(["a: http://domain.tld"]), ?checkError( {bad_url, {unsupported_scheme, http}, <<"http://domain.tld">>}, yconf:parse(File, #{a => yconf:url([https])})). bad_url_host_test() -> File = file(["a: http:///path"]), ?checkError( {bad_url, empty_host, <<"http:///path">>}, yconf:parse(File, #{a => yconf:url()})). bad_url_test() -> File = file(["a: bad"]), ?checkError( {bad_url, _, <<"bad">>}, yconf:parse(File, #{a => yconf:url()})). octal_test() -> File = file(["a: \"644\""]), ?assertEqual( {ok, [{a, 420}]}, yconf:parse(File, #{a => yconf:octal()})). bad_octal_test() -> File = file(["a: \"9\""]), ?checkError( {bad_octal, <<"9">>}, yconf:parse(File, #{a => yconf:octal()})). ipv4_test() -> File = file(["a: 127.0.0.1"]), ?assertEqual( {ok, [{a, {127,0,0,1}}]}, yconf:parse(File, #{a => yconf:ipv4()})). bad_ipv4_test() -> File = file(["a: '::1'"]), ?checkError( {bad_ipv4, "::1"}, yconf:parse(File, #{a => yconf:ipv4()})). ipv6_test() -> File = file(["a: '::1'"]), ?assertEqual( {ok, [{a, {0,0,0,0,0,0,0,1}}]}, yconf:parse(File, #{a => yconf:ipv6()})). bad_ipv6_test() -> File = file(["a: 127.0.0.1"]), ?checkError( {bad_ipv6, "127.0.0.1"}, yconf:parse(File, #{a => yconf:ipv6()})). ip_test() -> File = file(["a: 127.0.0.1", "b: '::1'"]), ?assertEqual( {ok, [{a, {127,0,0,1}}, {b, {0,0,0,0,0,0,0,1}}]}, yconf:parse(File, #{a => yconf:ip(), b => yconf:ip()})). bad_ip_test() -> File = file(["a: bad"]), ?checkError( {bad_ip, "bad"}, yconf:parse(File, #{a => yconf: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( {ok, [{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}}]}, yconf:parse(File, #{a => yconf:ip_mask(), b => yconf:ip_mask(), c => yconf:ip_mask(), d => yconf:ip_mask(), e => yconf:ip_mask(), f => yconf:ip_mask()})). bad_ip_mask_test() -> File = file(["a: 127.0.0.1/128"]), ?checkError( {bad_ip_mask, "127.0.0.1/128"}, yconf:parse(File, #{a => yconf:ip_mask()})). port_test() -> File = file(["a: 1", "b: 65535"]), ?assertEqual( {ok, [{a, 1}, {b, 65535}]}, yconf:parse(File, #{a => yconf:port(), b => yconf:port()})). timeout_test() -> File = file(["millisecond: 1", "second: 1", "minute: 1", "hour: 1", "day: 1"]), ?assertEqual( {ok, [{millisecond, 1}, {second, 1000}, {minute, 60000}, {hour, 3600000}, {day, 86400000}]}, yconf:parse(File, #{millisecond => yconf:timeout(millisecond), second => yconf:timeout(second), minute => yconf:timeout(minute), hour => yconf:timeout(hour), day => yconf:timeout(day)})). timeout_atom_test() -> File = file(["a: '5'"]), ?assertEqual( {ok, [{a, 5}]}, yconf:parse(File, #{a => yconf:timeout(millisecond)}, [plain_as_atom])). 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( {ok, [{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}]}, yconf:parse(File, #{'_' => yconf:timeout(millisecond)})). timeout_infinity_test() -> File = file(["a: infinity", "b: infinite", "c: unlimited"]), ?assertEqual( {ok, [{a, infinite}, {b, unlimited}, {c, infinity}]}, yconf:parse(File, #{a => yconf:timeout(day, infinite), b => yconf:timeout(day, unlimited), c => yconf:timeout(day, infinity)})). bad_timeout_test() -> File = file(["a: []"]), ?checkError( {bad_timeout, []}, yconf:parse(File, #{a => yconf:timeout(second)})), ?checkError( {bad_timeout, infinity, []}, yconf:parse(File, #{a => yconf:timeout(second, infinity)})). bad_timeout_zero_test() -> File = file(["a: 0"]), ?checkError( {bad_pos_int, 0}, yconf:parse(File, #{a => yconf:timeout(second)})), ?checkError( {bad_pos_int, infinity, 0}, yconf:parse(File, #{a => yconf:timeout(second, infinity)})). bad_timeout_infinity_test() -> File = file(["a: foo"]), ?checkError( {bad_int, <<"foo">>}, yconf:parse(File, #{a => yconf:timeout(second)})), ?checkError( {bad_enum, _, foo}, yconf:parse(File, #{a => yconf:timeout(second, infinity)})). bad_timeout_unit_test() -> File = file(["a: 1foo"]), ?checkError( {bad_timeout_unit, "foo"}, yconf:parse(File, #{a => yconf:timeout(second)})). bad_timeout_min_test() -> File = file(["a: 1ms"]), ?checkError( {bad_timeout_min, second}, yconf:parse(File, #{a => yconf:timeout(second)})). bad_timeout_negative_test() -> File = file(["a: -1s"]), ?checkError( {bad_pos_int, -1}, yconf:parse(File, #{a => yconf:timeout(second)})), ?checkError( {bad_pos_int, infinity, -1}, yconf:parse(File, #{a => yconf:timeout(second, infinity)})). re_test() -> File = file(["a: ^[0-9]+$"]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:re()})). bad_re_test() -> File = file(["a: '['"]), ?checkError( {bad_regexp, {_, _}, _}, yconf:parse(File, #{a => yconf:re()})). glob_test() -> File = file(["a: '*'"]), ?assertMatch( {ok, [{a, _}]}, yconf:parse(File, #{a => yconf:glob()})). bad_glob_test() -> File = file(["a: '['"]), ?checkError( {bad_glob, {_, _}, _}, yconf:parse(File, #{a => yconf:glob()})). beam_test() -> Exports = [[{foo, 1}, {parse, 2}], {parse, 3}, []], File = file(["a: yconf"]), ?assertMatch( {ok, [{a, yconf}]}, yconf:parse(File, #{a => yconf:beam(Exports)})). bad_beam_test() -> File = file(["a: foo"]), ?checkError( {bad_module, foo}, yconf:parse(File, #{a => yconf:beam()})), File = file(["a: yconf"]), ?checkError( {bad_export, {foo, 1}, yconf}, yconf:parse(File, #{a => yconf:beam([[{foo, 1}, {bar, 2}]])})), ?checkError( {bad_export, {foo, 1}, yconf}, yconf:parse(File, #{a => yconf:beam([{foo, 1}])})). non_empty_test() -> File = file(["a: [1,2,3]", "b: 1", "c: foo", "d: {e: f}"]), ?assertMatch( {ok, [{a, [1,2,3]}, {b, 1}, {c, foo}, {d, [_]}]}, yconf:parse(File, #{a => yconf:non_empty(yconf:list(yconf:int())), b => yconf:non_empty(yconf:int()), c => yconf:non_empty(yconf:atom()), d => yconf:non_empty(yconf:map(yconf:any(), yconf:any()))})). empty_atom_test() -> File = file(["a: ''"]), ?checkError( empty_atom, yconf:parse(File, #{a => yconf:non_empty(yconf:atom())})). empty_binary_test() -> File = file(["a: ''"]), ?checkError( empty_binary, yconf:parse(File, #{a => yconf:non_empty(yconf:binary())})). empty_list_test() -> File = file(["a: []"]), ?checkError( empty_list, yconf:parse(File, #{a => yconf:non_empty(yconf:list(yconf:any()))})). empty_map_test() -> File = file(["a: {}"]), ?checkError( empty_list, yconf:parse(File, #{a => yconf:non_empty( yconf:map(yconf:any(), yconf:any()))})). list_test() -> File = file(["a: [1,2,3]"]), ?assertMatch( {ok, [{a, [1,2,3]}]}, yconf:parse(File, #{a => yconf:list(yconf:any())})). bad_list_test() -> File = file(["a: 1"]), ?checkError( {bad_list, 1}, yconf:parse(File, #{a => yconf:list(yconf:any())})). sorted_list_test() -> File = file(["a: [3,2,1]"]), ?assertMatch( {ok, [{a, [1,2,3]}]}, yconf:parse(File, #{a => yconf:list(yconf:any(), [sorted])})). bad_sorted_list_test() -> File = file(["a: 1"]), ?checkError( {bad_list, 1}, yconf:parse(File, #{a => yconf:list(yconf:any(), [sorted])})). unique_list_test() -> File = file(["a: [1,2,3]"]), ?assertMatch( {ok, [{a, [1,2,3]}]}, yconf:parse(File, #{a => yconf:list(yconf:any(), [unique])})). bad_unique_list_test() -> File = file(["a: [1,2,1,3]"]), ?checkError( {duplicated_value, 1}, yconf:parse(File, #{a => yconf:list(yconf:any(), [unique])})), File = file(["a: [foo, bar, foo]"]), ?checkError( {duplicated_value, foo}, yconf:parse(File, #{a => yconf:list(yconf:atom(), [unique])})), File = file(["a: [[1], [2], [1]]"]), ?checkError( {duplicated_value, [1]}, yconf:parse(File, #{a => yconf:list(yconf:any(), [unique])})). list_or_single_test() -> File = file(["a: 1", "b: [1,2,3]"]), ?assertMatch( {ok, [{a, [1]}, {b, [1,2,3]}]}, yconf:parse(File, #{a => yconf:list_or_single(yconf:any()), b => yconf:list_or_single(yconf:any())})). sorted_list_or_single_test() -> File = file(["a: 1", "b: [3,2,1]"]), ?assertMatch( {ok, [{a, [1]}, {b, [1,2,3]}]}, yconf:parse(File, #{a => yconf:list_or_single(yconf:any(), [sorted]), b => yconf:list_or_single(yconf:any(), [sorted])})). unique_list_or_single_test() -> File = file(["a: 1", "b: [1,2,3]"]), ?assertMatch( {ok, [{a, [1]}, {b, [1,2,3]}]}, yconf:parse(File, #{a => yconf:list_or_single(yconf:any(), [unique]), b => yconf:list_or_single(yconf:any(), [unique])})). bad_unique_list_or_single_test() -> File = file(["a: 1", "b: [1,2,1,3]"]), ?checkError( {duplicated_value, 1}, yconf:parse(File, #{a => yconf:list_or_single(yconf:any(), [unique]), b => yconf:list_or_single(yconf:any(), [unique])})). map_test() -> File = file(["a: {c: 2, b: 1}"]), ?assertEqual( {ok, [{a, [{c, 2}, {b, 1}]}]}, yconf:parse(File, #{a => yconf:map(yconf:atom(), yconf:any())})), ?assertEqual( {ok, [{a, [{c, 2}, {b, 1}]}]}, yconf:parse(File, #{a => yconf:map(yconf:atom(), yconf:any(), [unique])})), ?assertEqual( {ok, [{a, [{b, 1}, {c, 2}]}]}, yconf:parse(File, #{a => yconf:map(yconf:atom(), yconf:any(), [{return, orddict}])})), ?assertEqual( {ok, [{a, #{b => 1, c => 2}}]}, yconf:parse(File, #{a => yconf:map(yconf:atom(), yconf:any(), [{return, map}])})), Ret = yconf:parse(File, #{a => yconf:map(yconf:atom(), yconf:any(), [{return, dict}])}), ?assertMatch({ok, [{a, _}]}, Ret), ?assertEqual( [{b, 1}, {c, 2}], lists:keysort(1, dict:to_list(element(2, hd(element(2, Ret)))))). bad_map_test() -> V = yconf:map(yconf:atom(), yconf:any()), File = file(["a: 1"]), ?checkError( {bad_map, 1}, yconf:parse(File, #{a => V})), File = file(["a: [1,2,3]"]), ?checkError( {bad_map, [1,2,3]}, yconf:parse(File, #{a => V})). bad_unique_map_test() -> File = file(["a: {c: 2, b: 1, c: 3}"]), ?checkError( {duplicated_key, c}, yconf:parse(File, #{a => yconf:map(yconf:atom(), yconf:any(), [unique])})). either_test() -> V = yconf:either(yconf:bool(), yconf:int()), File = file(["a: true", "b: 5"]), ?assertEqual( {ok, [{a, true}, {b, 5}]}, yconf:parse(File, #{a => V, b => V})). either_atom_test() -> V = yconf:either(atom, yconf:int()), File = file(["a: atom", "b: 1"]), ?assertEqual( {ok, [{a, atom}, {b, 1}]}, yconf:parse(File, #{a => V, b => V})). and_then_test() -> V = yconf:and_then( yconf:list(yconf:int()), fun lists:sum/1), File = file(["a: [1,2,3]"]), ?assertEqual( {ok, [{a, 6}]}, yconf:parse(File, #{a => V})). options_test() -> File = file(["a: {b: 1, c: true}"]), ?assertEqual( {ok, [{a, [{b, 1}, {c, true}]}]}, yconf:parse(File, #{a => yconf:options( #{b => yconf:int(), c => yconf:bool(), d => yconf:atom()})})). options_return_map_test() -> File = file(["a: 1", "b: 2"]), ?assertEqual( {ok, #{a => 1, b => 2}}, yconf:parse(File, #{a => yconf:any(), b => yconf:any()}, [{return, map}])). options_return_dict_test() -> File = file(["a: 1", "b: 2"]), Ret = yconf:parse(File, #{a => yconf:any(), b => yconf:any()}, [{return, dict}]), ?assertMatch({ok, _}, Ret), ?assertEqual( [{a, 1}, {b, 2}], lists:keysort(1, dict:to_list(element(2, Ret)))). options_return_orddict_test() -> File = file(["b: 1", "a: 2"]), ?assertEqual( {ok, [{a, 2}, {b, 1}]}, yconf:parse(File, #{a => yconf:any(), b => yconf:any()}, [{return, orddict}])). options_default_validator_test() -> File = file(["a: {b: 1, c: true}"]), ?assertEqual( {ok, [{a, [{b, 1}, {c, true}]}]}, yconf:parse(File, #{a => yconf:options( #{b => yconf:int(), '_' => yconf:bool()})})). bad_options_test() -> File = file(["a: 1"]), ?checkError( {bad_map, 1}, yconf:parse(File, #{a => yconf:options(#{})})), File = file(["a: [1,2,3]"]), ?checkError( {bad_map, [1,2,3]}, yconf:parse(File, #{a => yconf:options(#{})})). bad_binary_map_option_test() -> File = file(["a: {b: foo}"]), ?checkError( {bad_bool, foo}, yconf:parse(File, #{a => yconf:map(yconf:binary(), yconf:bool())})). bad_integer_map_option_test() -> File = file(["a: {1: foo}"]), ?checkError( {bad_bool, foo}, yconf:parse(File, #{a => yconf:map(yconf:int(), yconf:bool())})). unknown_option_test() -> File = file(["a: 1"]), ?checkError( {unknown_option, [define_macro], a}, yconf:parse(File, #{}, [replace_macros])). missing_option_test() -> File = file(["a: 1"]), ?checkError( {missing_option, b}, yconf:parse(File, #{a => yconf:int(), b => yconf:any()}, [{required, [b]}])). disallowed_option_test() -> File = file(["a: 1", "b: 2"]), ?checkError( {disallowed_option, b}, yconf:parse(File, #{a => yconf:int()}, [{disallowed, [b]}])), ?checkError( {disallowed_option, b}, yconf:parse(File, #{a => yconf:int(), b => yconf:int()}, [{disallowed, [b]}])), ?checkError( {disallowed_option, b}, yconf:parse(File, #{a => yconf:int(), b => yconf:int()}, [{required, [b]}, {disallowed, [b]}])). unknown_option_with_disallowed_test() -> File = file(["a: 1", "c: 2"]), ?checkError( {unknown_option, [a], c}, yconf:parse(File, #{a => yconf:int(), b => yconf:int()}, [{disallowed, [b]}])). duplicated_option_test() -> File = file(["a: 1", "b: 2", "a: 3"]), ?checkError( {duplicated_option, a}, yconf:parse(File, #{a => yconf:int(), b => yconf:int()}, [unique])), ?assertEqual( {ok, [{a, 1}, {b, 2}, {a, 3}]}, yconf:parse(File, #{a => yconf:int(), b => yconf:int()}, [])). duplicated_unknown_option_test() -> File = file(["a: 1", "b: 2", "b: 3"]), ?checkError( {duplicated_option, b}, yconf:parse(File, #{a => yconf:int(), '_' => yconf:any()}, [unique])). 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), File = file(["a: " ++ UTF8CharList, "b: " ++ UTF8CharList]), ?assertEqual( {ok, [{a, UTF8CharAtom}, {b, UTF8CharBin}]}, yconf:parse(File, #{a => yconf:atom(), b => yconf:binary()}, [plain_as_atom])), ?assertEqual( {ok, [{a, UTF8CharAtom}, {b, UTF8CharBin}]}, yconf:parse(File, #{a => yconf:atom(), b => yconf:binary()})). stop_test() -> ?assertEqual(ok, yconf:stop()). %%%=================================================================== %%% Internal functions %%%=================================================================== test_dir() -> {ok, Cwd} = file:get_cwd(), CwdClean = case lists:reverse(filename:split(Cwd)) of [".eunit" | Tail] -> Tail; % when using rebar2 Tail -> Tail % when using rebar3 end, filename:join(lists:reverse(["test" | CwdClean])). file(Data) -> file("test.yml", Data). included_file(Data) -> file("included.yml", Data). file(FileName, Data) -> Path = filename:join(test_dir(), FileName), ok = file:write_file(Path, string:join(Data, io_lib:nl())), Path. test_format_error({error, Why, Ctx}) -> ?assertMatch([_|_], yconf:format_error(Why, Ctx)). yconf-1.0.12/LICENSE0000644000232200023220000002613614075762024014303 0ustar debalancedebalance 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.