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.

293 lines
11 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. %% for internal use only
  100. -export([info/2]).
  101. -include("rebar.hrl").
  102. -define(PROVIDER, compile).
  103. -define(DEPS, []).
  104. %% ===================================================================
  105. %% Public API
  106. %% ===================================================================
  107. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  108. init(State) ->
  109. State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER},
  110. {module, ?MODULE},
  111. {namespace, erlydtl},
  112. {bare, false},
  113. {deps, ?DEPS},
  114. {example, "rebar3 erlydtl compile"},
  115. {short_desc, "Compile erlydtl templates."},
  116. {desc, ""},
  117. {opts, []}])),
  118. {ok, State1}.
  119. do(Config) ->
  120. MultiDtlOpts = erlydtl_opts(Config),
  121. Result = lists:foldl(fun(DtlOpts, _) ->
  122. file:make_dir(option(out_dir, DtlOpts)),
  123. rebar_base_compiler:run(Config, [],
  124. option(doc_root, DtlOpts),
  125. option(source_ext, DtlOpts),
  126. option(out_dir, DtlOpts),
  127. option(module_ext, DtlOpts) ++ ".beam",
  128. fun(S, T, C) ->
  129. compile_dtl(C, S, T, DtlOpts)
  130. end,
  131. [{check_last_mod, false},
  132. {recursive, option(recursive, DtlOpts)}])
  133. end, ok, MultiDtlOpts),
  134. {Result, Config}.
  135. -spec format_error(any()) -> iolist().
  136. format_error(Reason) ->
  137. io_lib:format("~p", [Reason]).
  138. %% ===================================================================
  139. %% Internal functions
  140. %% ===================================================================
  141. info(help, compile) ->
  142. ?CONSOLE(
  143. "Build ErlyDtl (*.dtl) sources.~n"
  144. "~n"
  145. "Valid rebar.config options:~n"
  146. " ~p",
  147. [
  148. {erlydtl_opts, [{doc_root, "templates"},
  149. {out_dir, "ebin"},
  150. {source_ext, ".dtl"},
  151. {module_ext, "_dtl"},
  152. {recursive, true}]}
  153. ]).
  154. erlydtl_opts(Config) ->
  155. Opts = rebar_state:get(Config, erlydtl_opts, []),
  156. Tuples = [{K,V} || {K,V} <- Opts],
  157. case [L || L <- Opts, is_list(L), not io_lib:printable_list(L)] of
  158. [] ->
  159. [lists:keysort(1, Tuples)];
  160. Lists ->
  161. lists:map(
  162. fun(L) ->
  163. lists:keysort(1,
  164. lists:foldl(
  165. fun({K,T}, Acc) ->
  166. lists:keystore(K, 1, Acc, {K, T})
  167. end, Tuples, L))
  168. end, Lists)
  169. end.
  170. option(Opt, DtlOpts) ->
  171. proplists:get_value(Opt, DtlOpts, default(Opt)).
  172. default(doc_root) -> "templates";
  173. default(out_dir) -> "ebin";
  174. default(source_ext) -> ".dtl";
  175. default(module_ext) -> "_dtl";
  176. default(custom_tags_dir) -> "";
  177. default(compiler_options) -> [return];
  178. default(recursive) -> true.
  179. compile_dtl(Config, Source, Target, DtlOpts) ->
  180. case code:which(erlydtl) of
  181. non_existing ->
  182. ?ERROR("~n===============================================~n"
  183. " You need to install erlydtl to compile DTL templates~n"
  184. " Download the latest tarball release from github~n"
  185. " https://github.com/erlydtl/erlydtl/releases~n"
  186. " and install it into your erlang library dir~n"
  187. "===============================================~n", []),
  188. ?FAIL;
  189. _ ->
  190. case needs_compile(Source, Target, DtlOpts) of
  191. true ->
  192. do_compile(Config, Source, Target, DtlOpts);
  193. false ->
  194. skipped
  195. end
  196. end.
  197. do_compile(Config, Source, Target, DtlOpts) ->
  198. %% TODO: Check last mod on target and referenced DTLs here..
  199. %% erlydtl >= 0.8.1 does not use the extra indirection using the
  200. %% compiler_options. Kept for backward compatibility with older
  201. %% versions of erlydtl.
  202. CompilerOptions = option(compiler_options, DtlOpts),
  203. Sorted = proplists:unfold(
  204. lists:sort(
  205. [{out_dir, option(out_dir, DtlOpts)},
  206. {doc_root, option(doc_root, DtlOpts)},
  207. {custom_tags_dir, option(custom_tags_dir, DtlOpts)},
  208. {compiler_options, CompilerOptions}
  209. |CompilerOptions])),
  210. %% ensure that doc_root and out_dir are defined,
  211. %% using defaults if necessary
  212. Opts = lists:ukeymerge(1, DtlOpts, Sorted),
  213. ?INFO("Compiling \"~s\" -> \"~s\" with options:~n ~s",
  214. [Source, Target, io_lib:format("~p", [Opts])]),
  215. case erlydtl:compile_file(ec_cnv:to_list(Source),
  216. list_to_atom(module_name(Target)),
  217. Opts) of
  218. {ok, _Mod} ->
  219. ok;
  220. {ok, _Mod, Ws} ->
  221. rebar_base_compiler:ok_tuple(Config, Source, Ws);
  222. error ->
  223. rebar_base_compiler:error_tuple(Config, Source, [], [], Opts);
  224. {error, Es, Ws} ->
  225. rebar_base_compiler:error_tuple(Config, Source, Es, Ws, Opts)
  226. end.
  227. module_name(Target) ->
  228. F = filename:basename(Target),
  229. string:substr(F, 1, length(F)-length(".beam")).
  230. needs_compile(Source, Target, DtlOpts) ->
  231. LM = filelib:last_modified(Target),
  232. LM < filelib:last_modified(Source) orelse
  233. lists:any(fun(D) -> LM < filelib:last_modified(D) end,
  234. referenced_dtls(Source, DtlOpts)).
  235. referenced_dtls(Source, DtlOpts) ->
  236. DtlOpts1 = lists:keyreplace(doc_root, 1, DtlOpts,
  237. {doc_root, filename:dirname(Source)}),
  238. Set = referenced_dtls1([Source], DtlOpts1,
  239. sets:add_element(Source, sets:new())),
  240. sets:to_list(sets:del_element(Source, Set)).
  241. referenced_dtls1(Step, DtlOpts, Seen) ->
  242. ExtMatch = re:replace(option(source_ext, DtlOpts), "\.", "\\\\\\\\.",
  243. [{return, list}]),
  244. ShOpts = [{use_stdout, false}, return_on_error],
  245. AllRefs =
  246. lists:append(
  247. [begin
  248. Cmd = lists:flatten(["grep -o [^\\\"]*\\",
  249. ExtMatch, "[^\\\"]* ", F]),
  250. case rebar_utils:sh(Cmd, ShOpts) of
  251. {ok, Res} ->
  252. string:tokens(Res, "\n");
  253. {error, _} ->
  254. ""
  255. end
  256. end || F <- Step]),
  257. DocRoot = option(doc_root, DtlOpts),
  258. WithPaths = [ filename:join([DocRoot, F]) || F <- AllRefs ],
  259. ?DEBUG("All deps: ~p\n", [WithPaths]),
  260. Existing = [F || F <- WithPaths, filelib:is_regular(F)],
  261. New = sets:subtract(sets:from_list(Existing), Seen),
  262. case sets:size(New) of
  263. 0 -> Seen;
  264. _ -> referenced_dtls1(sets:to_list(New), DtlOpts,
  265. sets:union(New, Seen))
  266. end.