-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.erl
245 lines (179 loc) · 7.87 KB
/
template.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
%% Copyright (c) 2011-2017, Stefan Hellkvist <stefan@hellkvist.org>
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%%
%% @author Stefan Hellkvist <stefan@hellkvist.org> [https://blog.hellkvist.org/]
%% @copyright 2011-2017 Stefan Hellkvist
%% @doc Simple replace/match functions for templates. The module gives you either a
%% function to replace placeholders inside a template string given a dictionary or
%% a function for matching out variable values given a template string and a string.
%% Variables are always on the form $(VARIABLE_NAME)
-module(template).
-export([replace/2, match/2]).
%% api
%% @doc replaces variables inside the template string with the values defined by the dictionary
%% @param Template A template string, possibly containing variables on the form $(VARIABLE_NAME)
%% @param Dictionary A map with keys matching the variable names in the template string and with values being strings
%% @returns A list where all variables have been substituted or an error tuple if an error was found
-spec replace(list(), map()) -> list() | {error, any()}.
replace(Template, Dictionary) ->
try
replace(Template, [], Dictionary)
catch
error:{badkey, K} ->
{error, {bad_key, K}};
error:{badmatch, {error, eof}} ->
{error, eof}
end.
%% @doc given a template string and a string to match the template against, this extracts a map of variables which
%% satisfies the match
%% @param Template A template string, possibly containing variables on the form $(VARIABLE_NAME)
%% @param String A string that the template will be matched against
%% @returns A map where all variables in the template are keys with values that satisfies the map or an error tuple if an error was found
-spec match(list(), list()) -> map() | {error, any()}.
match(Template, String) ->
try
match(Template, String, #{}, {Template, String})
catch
error:{badmatch,{error,eof}} ->
{error, eof}
end.
%%% internal functions
replace([], Result, _Dict) ->
lists:reverse(lists:flatten(Result));
replace("$(" ++ Rest, Result, Dict) ->
{ok, VarName, RemainsAfterVariable} = read_var_name(Rest),
Value = maps:get(VarName, Dict),
replace(RemainsAfterVariable, [lists:reverse(Value) | Result], Dict);
replace([C | RestTemplate], Result, Dict) ->
replace(RestTemplate, [C | Result], Dict).
match([], [], D, _) ->
D;
match("$(" ++ Rest, String, D, Arg) ->
{ok, VarName, RemainsAfterVariable} = read_var_name(Rest),
case maps:get(VarName, D, undefined) of
undefined -> %% if we don't have an existing binding we try all possible bindings
bind(VarName, [], RemainsAfterVariable, String, D, Arg);
CurrentValue -> %% if we have an existing binding we substitute the value of the variable and try to match
match(lists:flatten([CurrentValue | RemainsAfterVariable]), String, D, Arg)
end;
match([C | TemplateRest], [C | StringRest], D, Arg) ->
match(TemplateRest, StringRest, D, Arg);
match(_, _, _, Arg) ->
{error, {no_match, Arg}}.
bind(VarName, Value, [], [], D, _) ->
D#{VarName => lists:reverse(Value)};
bind(VarName, _, [], String, D, _) when length(String) > 0 ->
D#{VarName => String};
bind(VarName, Value, Template, [], D, Arg) when length(Template) > 0 ->
NewD = D#{VarName => lists:reverse(Value)},
match(Template, [], NewD, Arg);
bind(VarName, AccValue, String, String, D, _) ->
D#{VarName => lists:reverse(AccValue)};
bind(VarName, AccValue, Template, [C | StringRest] = String, D, Arg) ->
NewD = D#{VarName => lists:reverse(AccValue)},
case match(Template, String, NewD, Arg) of
{error, _Reason} ->
bind(VarName, [C | AccValue], Template, StringRest, D, Arg);
YetAnotherD ->
YetAnotherD
end.
%% reads out the variable name from a string where the string starts after the "$(" part of the variable
read_var_name(String) ->
read_var_name(String, []).
read_var_name([], _Res) ->
{error, eof};
read_var_name([$) | Remain], Res) ->
{ok, lists:reverse(Res), Remain};
read_var_name([C | Remain], Res) ->
read_var_name(Remain, [C | Res]).
%%% EUNIT tests %%%%
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
%% replace tests
noreplace_test() ->
?assertEqual("Hello", template:replace("Hello", #{})).
onereplace_test() ->
?assertEqual("Hello", template:replace("$(A)", #{"A" => "Hello"})).
tworeplace_test() ->
?assertEqual("Hello mr X and mrs Y",
template:replace("Hello $(A) and $(B)",
#{"A" => "mr X",
"B" => "mrs Y"})).
same_replace_test() ->
?assertEqual("1+1=11",
template:replace("$(A)+$(A)=$(A)$(A)",
#{"A" => "1"})).
not_found_test() ->
?assertEqual({error, {bad_key, "A"}},
template:replace("$(A)", #{})).
non_terminated_key_test() ->
?assertEqual({error, eof},
template:replace("$(A", #{})).
%% match tests
match_no_variables_test() ->
D = match("abc", "abc"),
?assertEqual([], maps:keys(D)).
match_empty_strings_test() ->
D = match("", ""),
?assertEqual([], maps:keys(D)).
match_no_match_no_variables_test() ->
?assertEqual({error, {no_match, {"abc", "123"}}}, match("abc", "123")).
match_no_match_no_variables2_test() ->
?assertEqual({error, {no_match, {"abc", ""}}}, match("abc", "")).
match_only_one_variable_test() ->
D = match("$(A)", "abc"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("abc", maps:get("A", D)).
match_one_variable_at_beginning_with_remainder_test() ->
D = match("$(A)abc", "abc"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("", maps:get("A", D)).
match_one_variable_at_end_test() ->
D = match("abc$(A)", "abc"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("", maps:get("A", D)).
match_one_variable_in_middle_test() ->
D = match("abc$(A)def", "abc123def"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("123", maps:get("A", D)).
match_two_variables_test() ->
D = match("abc$(A)#$(B)def", "abc123#321def"),
?assertEqual(["A", "B"], maps:keys(D)),
?assertEqual("123", maps:get("A", D)),
?assertEqual("321", maps:get("B", D)).
match_two_times_test() ->
D = match("a$(A)$(A)a", "abba"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("b", maps:get("A", D)).
match_bad_variable_test() ->
?assertEqual({error, eof}, match("$(A", def)).
match_no_match_test() ->
?assertEqual({error, {no_match, {"$(A)a", "b"}}}, match("$(A)a", "b")).
match_no_match2_test() ->
?assertEqual({error, {no_match, {"a$(A)a$(A)", "abac"}}}, match("a$(A)a$(A)", "abac")).
match_full_string_to_one_variable_test() ->
D = match("$(_BODY)", "some string"),
?assertEqual("some string", maps:get("_BODY", D)).
match_conflict_test() ->
D = match("$(A)$(A)", "ab"),
?assertEqual({error, {no_match, {"$(A)$(A)", "ab"}}}, D).
match_three_test() ->
D = match("$(A)$(A)$(A)", "ababab"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("ab", maps:get("A", D)).
match_with_variable_pattern_test() ->
D = match("$(A)", "$(A)"),
?assertEqual(["A"], maps:keys(D)),
?assertEqual("$(A)", maps:get("A", D)).
-endif.