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.

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