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.

270 lines
10 KiB

  1. %% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
  2. %% ex: ts=4 sw=4 et
  3. %% -------------------------------------------------------------------
  4. %%
  5. %% rebar: Erlang Build Tools
  6. %%
  7. %% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.com),
  8. %% Bryan Fink (bryan@basho.com)
  9. %%
  10. %% Permission is hereby granted, free of charge, to any person obtaining a copy
  11. %% of this software and associated documentation files (the "Software"), to deal
  12. %% in the Software without restriction, including without limitation the rights
  13. %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. %% copies of the Software, and to permit persons to whom the Software is
  15. %% furnished to do so, subject to the following conditions:
  16. %%
  17. %% The above copyright notice and this permission notice shall be included in
  18. %% all copies or substantial portions of the Software.
  19. %%
  20. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. %% THE SOFTWARE.
  27. %% -------------------------------------------------------------------
  28. %% The rebar_erlydtl_compiler module is a plugin for rebar that compiles
  29. %% ErlyDTL templates. By default, it compiles all templates/*.dtl
  30. %% to ebin/*_dtl.beam.
  31. %%
  32. %% Configuration options should be placed in rebar.config under
  33. %% 'erlydtl_opts'. It can be a list of name-value tuples or a list of
  34. %% lists of name-value tuples if you have multiple template directories
  35. %% that need to have different settings (see example below).
  36. %%
  37. %% Available options include:
  38. %%
  39. %% doc_root: where to find templates to compile
  40. %% "templates" by default
  41. %%
  42. %% out_dir: where to put compiled template beam files
  43. %% "ebin" by default
  44. %%
  45. %% source_ext: the file extension the template sources have
  46. %% ".dtl" by default
  47. %%
  48. %% module_ext: characters to append to the template's module name
  49. %% "_dtl" by default
  50. %%
  51. %% recursive: boolean that determines if doc_root(s) need to be
  52. %% scanned recursively for matching template file names
  53. %% (default: true).
  54. %% For example, if you had:
  55. %% /t_src/
  56. %% base.html
  57. %% foo.html
  58. %%
  59. %% And you wanted them compiled to:
  60. %% /priv/
  61. %% base.beam
  62. %% foo.beam
  63. %%
  64. %% You would add to your rebar.config:
  65. %% {erlydtl_opts, [
  66. %% {doc_root, "t_src"},
  67. %% {out_dir, "priv"},
  68. %% {source_ext, ".html"},
  69. %% {module_ext, ""}
  70. %% ]}.
  71. %%
  72. %% The default settings are the equivalent of:
  73. %% {erlydtl_opts, [
  74. %% {doc_root, "templates"},
  75. %% {out_dir, "ebin"},
  76. %% {source_ext, ".dtl"},
  77. %% {module_ext, "_dtl"}
  78. %% ]}.
  79. %%
  80. %% The following example will compile the following templates:
  81. %% "src/*.dtl" files into "ebin/*_dtl.beam" and
  82. %% "templates/*.html" into "ebin/*.beam". Note that any tuple option
  83. %% (such as 'out_dir') in the outer list is added to each inner list:
  84. %% {erlydtl_opts, [
  85. %% {out_dir, "ebin"},
  86. %% {recursive, false},
  87. %% [
  88. %% {doc_root, "src"}, {module_ext, "_dtl"}
  89. %% ],
  90. %% [
  91. %% {doc_root, "templates"}, {module_ext, ""}, {source_ext, ".html"}
  92. %% ]
  93. %% ]}.
  94. -module(rebar_prv_erlydtl_compiler).
  95. -behaviour(provider).
  96. -export([init/1,
  97. do/1,
  98. format_error/1]).
  99. -include("rebar.hrl").
  100. -include_lib("providers/include/providers.hrl").
  101. -define(PROVIDER, compile).
  102. -define(DEPS, [{default, compile}]).
  103. %% ===================================================================
  104. %% Public API
  105. %% ===================================================================
  106. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  107. init(State) ->
  108. State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER},
  109. {module, ?MODULE},
  110. {namespace, erlydtl},
  111. {bare, false},
  112. {deps, ?DEPS},
  113. {example, "rebar3 erlydtl compile"},
  114. {short_desc, "Compile erlydtl templates."},
  115. {desc, "Compile erlydtl templates."},
  116. {opts, []}])),
  117. {ok, State1}.
  118. do(State) ->
  119. ?INFO("Running erlydtl...", []),
  120. case rebar_state:get(State, escript_main_app, undefined) of
  121. undefined ->
  122. Dir = rebar_state:dir(State),
  123. case rebar_app_discover:find_app(Dir, all) of
  124. {true, AppInfo} ->
  125. AllApps = rebar_state:project_apps(State) ++ rebar_state:all_deps(State),
  126. case rebar_app_utils:find(rebar_app_info:name(AppInfo), AllApps) of
  127. {ok, AppInfo1} ->
  128. %% Use the existing app info instead of newly created one
  129. run_erlydtl(AppInfo1, State);
  130. _ ->
  131. run_erlydtl(AppInfo, State)
  132. end,
  133. {ok, State};
  134. _ ->
  135. ?PRV_ERROR(no_main_app)
  136. end;
  137. Name ->
  138. AllApps = rebar_state:project_apps(State) ++ rebar_state:all_deps(State),
  139. {ok, App} = rebar_app_utils:find(Name, AllApps),
  140. run_erlydtl(App, State),
  141. {ok, State}
  142. end.
  143. run_erlydtl(App, State) ->
  144. Dir = rebar_state:dir(State),
  145. DtlOpts = proplists:unfold(rebar_state:get(State, erlydtl_opts, [])),
  146. TemplateDir = filename:join(Dir, option(doc_root, DtlOpts)),
  147. DtlOpts2 = [{doc_root, TemplateDir} | proplists:delete(doc_root, DtlOpts)],
  148. OutDir = rebar_app_info:ebin_dir(App),
  149. filelib:ensure_dir(filename:join(OutDir, "dummy.beam")),
  150. rebar_base_compiler:run(State,
  151. [],
  152. TemplateDir,
  153. option(source_ext, DtlOpts2),
  154. OutDir,
  155. option(module_ext, DtlOpts2) ++ ".beam",
  156. fun(S, T, C) ->
  157. compile_dtl(C, S, T, DtlOpts2, Dir, OutDir)
  158. end,
  159. [{check_last_mod, false},
  160. {recursive, option(recursive, DtlOpts2)}]).
  161. -spec format_error(any()) -> iolist().
  162. format_error(no_main_app) ->
  163. "Erlydtl Error: Multiple project apps found and no {app, atom()} option found in erlydtl_opts.";
  164. format_error(Reason) ->
  165. io_lib:format("~p", [Reason]).
  166. %% ===================================================================
  167. %% Internal functions
  168. %% ===================================================================
  169. option(Opt, DtlOpts) ->
  170. proplists:get_value(Opt, DtlOpts, default(Opt)).
  171. default(app) -> undefined;
  172. default(doc_root) -> "priv/templates";
  173. default(source_ext) -> ".dtl";
  174. default(module_ext) -> "_dtl";
  175. default(custom_tags_dir) -> "";
  176. default(compiler_options) -> [return];
  177. default(recursive) -> true.
  178. compile_dtl(State, Source, Target, DtlOpts, Dir, OutDir) ->
  179. case needs_compile(Source, Target, DtlOpts) of
  180. true ->
  181. do_compile(State, Source, Target, DtlOpts, Dir, OutDir);
  182. false ->
  183. skipped
  184. end.
  185. do_compile(State, Source, Target, DtlOpts, Dir, OutDir) ->
  186. CompilerOptions = option(compiler_options, DtlOpts),
  187. Sorted = proplists:unfold(
  188. lists:sort(
  189. [{out_dir, OutDir},
  190. {doc_root, filename:join(Dir, option(doc_root, DtlOpts))},
  191. {custom_tags_dir, option(custom_tags_dir, DtlOpts)},
  192. {compiler_options, CompilerOptions}])),
  193. %% ensure that doc_root and out_dir are defined,
  194. %% using defaults if necessary
  195. Opts = lists:ukeymerge(1, DtlOpts, Sorted),
  196. ?DEBUG("Compiling \"~s\" -> \"~s\" with options:~n ~s",
  197. [Source, Target, io_lib:format("~p", [Opts])]),
  198. case erlydtl:compile_file(ec_cnv:to_list(Source),
  199. list_to_atom(module_name(Target)),
  200. Opts) of
  201. {ok, _Mod} ->
  202. ok;
  203. {ok, _Mod, Ws} ->
  204. rebar_base_compiler:ok_tuple(State, Source, Ws);
  205. error ->
  206. rebar_base_compiler:error_tuple(State, Source, [], [], Opts);
  207. {error, Es, Ws} ->
  208. rebar_base_compiler:error_tuple(State, Source, Es, Ws, Opts)
  209. end.
  210. module_name(Target) ->
  211. filename:rootname(filename:basename(Target), ".beam").
  212. needs_compile(Source, Target, DtlOpts) ->
  213. LM = filelib:last_modified(Target),
  214. LM < filelib:last_modified(Source) orelse
  215. lists:any(fun(D) -> LM < filelib:last_modified(D) end,
  216. referenced_dtls(Source, DtlOpts)).
  217. referenced_dtls(Source, DtlOpts) ->
  218. DtlOpts1 = lists:keyreplace(doc_root, 1, DtlOpts,
  219. {doc_root, filename:dirname(Source)}),
  220. Set = referenced_dtls1([Source], DtlOpts1,
  221. sets:add_element(Source, sets:new())),
  222. sets:to_list(sets:del_element(Source, Set)).
  223. referenced_dtls1(Step, DtlOpts, Seen) ->
  224. ExtMatch = re:replace(option(source_ext, DtlOpts), "\.", "\\\\\\\\.",
  225. [{return, list}]),
  226. ShOpts = [{use_stdout, false}, return_on_error],
  227. AllRefs =
  228. lists:append(
  229. [begin
  230. Cmd = lists:flatten(["grep -o [^\\\"]*\\",
  231. ExtMatch, "[^\\\"]* ", F]),
  232. case rebar_utils:sh(Cmd, ShOpts) of
  233. {ok, Res} ->
  234. string:tokens(Res, "\n");
  235. {error, _} ->
  236. ""
  237. end
  238. end || F <- Step]),
  239. DocRoot = option(doc_root, DtlOpts),
  240. WithPaths = [ filename:join([DocRoot, F]) || F <- AllRefs ],
  241. ?DEBUG("All deps: ~p\n", [WithPaths]),
  242. Existing = [F || F <- WithPaths, filelib:is_regular(F)],
  243. New = sets:subtract(sets:from_list(Existing), Seen),
  244. case sets:size(New) of
  245. 0 -> Seen;
  246. _ -> referenced_dtls1(sets:to_list(New), DtlOpts,
  247. sets:union(New, Seen))
  248. end.