Skip to content

Commit

Permalink
Allow included file values
Browse files Browse the repository at this point in the history
Allows defining .conf values in the format `$(<FILENAME)`, the included
file contents will be read and used as the setting value.
  • Loading branch information
lrascao committed Dec 3, 2020
1 parent 146684a commit 0de26f1
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
36 changes: 35 additions & 1 deletion src/cuttlefish_conf.erl
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ file(Filename) ->
{_, Values} = lists:unzip(Conf),
case cuttlefish_error:filter(Values) of
{errorlist, []} ->
remove_duplicates(Conf);
% expand any non-literal values (ie. included values)
expand_values(Filename, remove_duplicates(Conf));
{errorlist, ErrorList} ->
NewErrorList = [ {error, {in_file, {Filename, E}}} || {error, E} <- ErrorList ],
{errorlist, NewErrorList}
Expand All @@ -98,6 +99,31 @@ fold_conf_files(Filename, Conf0) ->
[],
Conf0).

expand_values(Filename, Conf) ->
lists:map(fun({K, Value0}) ->
case re:split(Value0, "[$(<)]") of
[_, _, _, IncludeFilename0, _] ->
% this is a value of the format "$(<IncludeFilename), let's read the contents
% of `IncludeFilename` and use that as the new value
%
% strip all space chars from beginning/end and join the relative filename with the
% location of the sourcing .conf file
IncludeFilename = filename:join([filename:dirname(Filename),
re:replace(IncludeFilename0, "[ ]", "", [global, {return, list}])]),
% read the entire file contents and strip newline
case file:read_file(IncludeFilename) of
{ok, Value} ->
{K, re:replace(Value, "[\n\r]", "", [global, {return, list}])};
{error, Reason} ->
throw({unable_to_open, IncludeFilename, Reason})
end;
_ ->
% normal value, nothing to do
{K, Value0}
end
end,
Conf).

-spec generate([cuttlefish_mapping:mapping()]) -> [string()].
generate(Mappings) ->
lists:foldl(
Expand Down Expand Up @@ -391,6 +417,14 @@ included_dir_test() ->
]), lists:sort(Conf)),
ok.

included_value_test() ->
Conf = file("test/included_value.conf"),
?assertEqual(lists:sort([
{["value1"],"42"},
{["value2"], "43"}
]), lists:sort(Conf)),
ok.

assert_no_output(Setting) ->
Mapping = cuttlefish_mapping:parse(
{mapping,
Expand Down
2 changes: 2 additions & 0 deletions test/included_value.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
value1 = $(<value1)
value2 = 43
1 change: 1 addition & 0 deletions test/value1
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
42

0 comments on commit 0de26f1

Please sign in to comment.