You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

230 lines
7.5 KiB

преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 12 години
преди 12 години
преди 14 години
преди 12 години
преди 12 години
преди 14 години
преди 14 години
  1. %% The MIT License
  2. %%
  3. %% Copyright (c) 2009 Tom Preston-Werner <tom@mojombo.com>
  4. %%
  5. %% Permission is hereby granted, free of charge, to any person obtaining a copy
  6. %% of this software and associated documentation files (the "Software"), to deal
  7. %% in the Software without restriction, including without limitation the rights
  8. %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. %% copies of the Software, and to permit persons to whom the Software is
  10. %% furnished to do so, subject to the following conditions:
  11. %%
  12. %% The above copyright notice and this permission notice shall be included in
  13. %% all copies or substantial portions of the Software.
  14. %%
  15. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. %% THE SOFTWARE.
  22. %% See the README at http://github.com/mojombo/mustache.erl for additional
  23. %% documentation and usage examples.
  24. -module(rebar_mustache). %% v0.1.0
  25. -author("Tom Preston-Werner").
  26. -export([compile/1, compile/2, render/1, render/2, render/3, get/2, get/3, escape/1, start/1]).
  27. -record(mstate, {mod = undefined,
  28. section_re = undefined,
  29. tag_re = undefined}).
  30. -define(MUSTACHE_STR, "rebar_mustache").
  31. compile(Body) when is_list(Body) ->
  32. State = #mstate{},
  33. CompiledTemplate = pre_compile(Body, State),
  34. % io:format("~p~n~n", [CompiledTemplate]),
  35. % io:format(CompiledTemplate ++ "~n", []),
  36. {ok, Tokens, _} = erl_scan:string(CompiledTemplate),
  37. {ok, [Form]} = erl_parse:parse_exprs(Tokens),
  38. Bindings = erl_eval:new_bindings(),
  39. {value, Fun, _} = erl_eval:expr(Form, Bindings),
  40. Fun;
  41. compile(Mod) ->
  42. TemplatePath = template_path(Mod),
  43. compile(Mod, TemplatePath).
  44. compile(Mod, File) ->
  45. code:purge(Mod),
  46. {module, _} = code:load_file(Mod),
  47. {ok, TemplateBin} = file:read_file(File),
  48. Template = re:replace(TemplateBin, "\"", "\\\\\"", [global, {return,list}]),
  49. State = #mstate{mod = Mod},
  50. CompiledTemplate = pre_compile(Template, State),
  51. % io:format("~p~n~n", [CompiledTemplate]),
  52. % io:format(CompiledTemplate ++ "~n", []),
  53. {ok, Tokens, _} = erl_scan:string(CompiledTemplate),
  54. {ok, [Form]} = erl_parse:parse_exprs(Tokens),
  55. Bindings = erl_eval:new_bindings(),
  56. {value, Fun, _} = erl_eval:expr(Form, Bindings),
  57. Fun.
  58. render(Mod) ->
  59. TemplatePath = template_path(Mod),
  60. render(Mod, TemplatePath).
  61. render(Body, Ctx) when is_list(Body) ->
  62. TFun = compile(Body),
  63. render(undefined, TFun, Ctx);
  64. render(Mod, File) when is_list(File) ->
  65. render(Mod, File, dict:new());
  66. render(Mod, CompiledTemplate) ->
  67. render(Mod, CompiledTemplate, dict:new()).
  68. render(Mod, File, Ctx) when is_list(File) ->
  69. CompiledTemplate = compile(Mod, File),
  70. render(Mod, CompiledTemplate, Ctx);
  71. render(Mod, CompiledTemplate, Ctx) ->
  72. Ctx2 = dict:store('__mod__', Mod, Ctx),
  73. lists:flatten(CompiledTemplate(Ctx2)).
  74. pre_compile(T, State) ->
  75. SectionRE = "\{\{\#([^\}]*)}}\s*(.+?){{\/\\1\}\}\s*",
  76. {ok, CompiledSectionRE} = re:compile(SectionRE, [dotall]),
  77. TagRE = "\{\{(#|=|!|<|>|\{)?(.+?)\\1?\}\}+",
  78. {ok, CompiledTagRE} = re:compile(TagRE, [dotall]),
  79. State2 = State#mstate{section_re = CompiledSectionRE, tag_re = CompiledTagRE},
  80. "fun(Ctx) -> " ++
  81. "CFun = fun(A, B) -> A end, " ++
  82. compiler(T, State2) ++ " end.".
  83. compiler(T, State) ->
  84. Res = re:run(T, State#mstate.section_re),
  85. case Res of
  86. {match, [{M0, M1}, {N0, N1}, {C0, C1}]} ->
  87. Front = string:substr(T, 1, M0),
  88. Back = string:substr(T, M0 + M1 + 1),
  89. Name = string:substr(T, N0 + 1, N1),
  90. Content = string:substr(T, C0 + 1, C1),
  91. "[" ++ compile_tags(Front, State) ++
  92. " | [" ++ compile_section(Name, Content, State) ++
  93. " | [" ++ compiler(Back, State) ++ "]]]";
  94. nomatch ->
  95. compile_tags(T, State)
  96. end.
  97. compile_section(Name, Content, State) ->
  98. Mod = State#mstate.mod,
  99. Result = compiler(Content, State),
  100. "fun() -> " ++
  101. "case " ++ ?MUSTACHE_STR ++ ":get(" ++ Name ++ ", Ctx, " ++ atom_to_list(Mod) ++ ") of " ++
  102. "\"true\" -> " ++
  103. Result ++ "; " ++
  104. "\"false\" -> " ++
  105. "[]; " ++
  106. "List when is_list(List) -> " ++
  107. "[fun(Ctx) -> " ++ Result ++ " end(dict:merge(CFun, SubCtx, Ctx)) || SubCtx <- List]; " ++
  108. "Else -> " ++
  109. "throw({template, io_lib:format(\"Bad context for ~p: ~p\", [" ++ Name ++ ", Else])}) " ++
  110. "end " ++
  111. "end()".
  112. compile_tags(T, State) ->
  113. Res = re:run(T, State#mstate.tag_re),
  114. case Res of
  115. {match, [{M0, M1}, K, {C0, C1}]} ->
  116. Front = string:substr(T, 1, M0),
  117. Back = string:substr(T, M0 + M1 + 1),
  118. Content = string:substr(T, C0 + 1, C1),
  119. Kind = tag_kind(T, K),
  120. Result = compile_tag(Kind, Content, State),
  121. "[\"" ++ Front ++
  122. "\" | [" ++ Result ++
  123. " | " ++ compile_tags(Back, State) ++ "]]";
  124. nomatch ->
  125. "[\"" ++ T ++ "\"]"
  126. end.
  127. tag_kind(_T, {-1, 0}) ->
  128. none;
  129. tag_kind(T, {K0, K1}) ->
  130. string:substr(T, K0 + 1, K1).
  131. compile_tag(none, Content, State) ->
  132. Mod = State#mstate.mod,
  133. ?MUSTACHE_STR ++ ":escape(" ++ ?MUSTACHE_STR ++ ":get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ "))";
  134. compile_tag("{", Content, State) ->
  135. Mod = State#mstate.mod,
  136. ?MUSTACHE_STR ++ ":get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ ")";
  137. compile_tag("!", _Content, _State) ->
  138. "[]".
  139. template_dir(Mod) ->
  140. DefaultDirPath = filename:dirname(code:which(Mod)),
  141. case application:get_env(mustache, templates_dir) of
  142. {ok, DirPath} when is_list(DirPath) ->
  143. case filelib:ensure_dir(DirPath) of
  144. ok -> DirPath;
  145. _ -> DefaultDirPath
  146. end;
  147. _ ->
  148. DefaultDirPath
  149. end.
  150. template_path(Mod) ->
  151. DirPath = template_dir(Mod),
  152. Basename = atom_to_list(Mod),
  153. filename:join(DirPath, Basename ++ ".mustache").
  154. get(Key, Ctx) when is_list(Key) ->
  155. {ok, Mod} = dict:find('__mod__', Ctx),
  156. get(list_to_atom(Key), Ctx, Mod);
  157. get(Key, Ctx) ->
  158. {ok, Mod} = dict:find('__mod__', Ctx),
  159. get(Key, Ctx, Mod).
  160. get(Key, Ctx, Mod) when is_list(Key) ->
  161. get(list_to_atom(Key), Ctx, Mod);
  162. get(Key, Ctx, Mod) ->
  163. case dict:find(Key, Ctx) of
  164. {ok, Val} ->
  165. % io:format("From Ctx {~p, ~p}~n", [Key, Val]),
  166. to_s(Val);
  167. error ->
  168. case erlang:function_exported(Mod, Key, 1) of
  169. true ->
  170. Val = to_s(Mod:Key(Ctx)),
  171. % io:format("From Mod/1 {~p, ~p}~n", [Key, Val]),
  172. Val;
  173. false ->
  174. case erlang:function_exported(Mod, Key, 0) of
  175. true ->
  176. Val = to_s(Mod:Key()),
  177. % io:format("From Mod/0 {~p, ~p}~n", [Key, Val]),
  178. Val;
  179. false ->
  180. []
  181. end
  182. end
  183. end.
  184. to_s(Val) when is_integer(Val) ->
  185. integer_to_list(Val);
  186. to_s(Val) when is_float(Val) ->
  187. io_lib:format("~.2f", [Val]);
  188. to_s(Val) when is_atom(Val) ->
  189. atom_to_list(Val);
  190. to_s(Val) ->
  191. Val.
  192. escape(HTML) ->
  193. escape(HTML, []).
  194. escape([], Acc) ->
  195. lists:reverse(Acc);
  196. escape(["<" | Rest], Acc) ->
  197. escape(Rest, lists:reverse("&lt;", Acc));
  198. escape([">" | Rest], Acc) ->
  199. escape(Rest, lists:reverse("&gt;", Acc));
  200. escape(["&" | Rest], Acc) ->
  201. escape(Rest, lists:reverse("&amp;", Acc));
  202. escape([X | Rest], Acc) ->
  203. escape(Rest, [X | Acc]).
  204. %%---------------------------------------------------------------------------
  205. start([T]) ->
  206. Out = render(list_to_atom(T)),
  207. io:format(Out ++ "~n", []).