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.

258 line
9.9 KiB

  1. %% -*- tab-width: 4;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. %%
  9. %% Permission is hereby granted, free of charge, to any person obtaining a copy
  10. %% of this software and associated documentation files (the "Software"), to deal
  11. %% in the Software without restriction, including without limitation the rights
  12. %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. %% copies of the Software, and to permit persons to whom the Software is
  14. %% furnished to do so, subject to the following conditions:
  15. %%
  16. %% The above copyright notice and this permission notice shall be included in
  17. %% all copies or substantial portions of the Software.
  18. %%
  19. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. %% THE SOFTWARE.
  26. %% -------------------------------------------------------------------
  27. -module(rebar_templater).
  28. -export(['create-app'/2,
  29. 'create-node'/2,
  30. create/2]).
  31. -include("rebar.hrl").
  32. -define(TEMPLATE_RE, ".*\\.template\$").
  33. %% ===================================================================
  34. %% Public API
  35. %% ===================================================================
  36. 'create-app'(Config, File) ->
  37. %% Alias for create w/ template=simpleapp
  38. rebar_config:set_global(template, "simpleapp"),
  39. create(Config, File).
  40. 'create-node'(Config, File) ->
  41. %% Alias for create w/ template=simplenode
  42. rebar_config:set_global(template, "simplenode"),
  43. create(Config, File).
  44. create(_Config, _) ->
  45. %% Load a list of all the files in the escript -- cache it in the pdict
  46. %% since we'll potentially need to walk it several times over the course
  47. %% of a run.
  48. cache_escript_files(),
  49. %% Build a list of available templates
  50. AvailTemplates = find_disk_templates() ++ find_escript_templates(),
  51. ?DEBUG("Available templates: ~p\n", [AvailTemplates]),
  52. %% Using the specified template id, find the matching template file/type.
  53. %% Note that if you define the same template in both ~/.rebar/templates
  54. %% that is also present in the escript, the one on the file system will
  55. %% be preferred.
  56. {Type, Template} = select_template(AvailTemplates, template_id()),
  57. %% Load the template definition as is and get the list of variables the
  58. %% template requires.
  59. TemplateTerms = consult(load_file(Type, Template)),
  60. case lists:keysearch(variables, 1, TemplateTerms) of
  61. {value, {variables, Vars}} ->
  62. case parse_vars(Vars, dict:new()) of
  63. {error, Entry} ->
  64. Context0 = undefined,
  65. ?ABORT("Failed while processing variables from template ~p. Variable definitions "
  66. "must follow form of [{atom(), term()}]. Failed at: ~p\n",
  67. [template_id(), Entry]);
  68. Context0 ->
  69. ok
  70. end;
  71. false ->
  72. ?WARN("No variables section found in template ~p; using empty context.\n",
  73. [template_id()]),
  74. Context0 = dict:new()
  75. end,
  76. %% For each variable, see if it's defined in global vars -- if it is, prefer that
  77. %% value over the defaults
  78. Context = update_vars(dict:fetch_keys(Context0), Context0),
  79. ?DEBUG("Template ~p context: ~p\n", [template_id(), dict:to_list(Context)]),
  80. %% Now, use our context to process the template definition -- this permits us to
  81. %% use variables within the definition for filenames.
  82. FinalTemplate = consult(render(load_file(Type, Template), Context)),
  83. ?DEBUG("Final template def ~p: ~p\n", [template_id(), FinalTemplate]),
  84. %% Execute the instructions in the finalized template
  85. Force = rebar_config:get_global(force, "0"),
  86. execute_template(FinalTemplate, Type, Template, Context, Force, []).
  87. %% ===================================================================
  88. %% Internal functions
  89. %% ===================================================================
  90. %%
  91. %% Scan the current escript for available files and cache in pdict.
  92. %%
  93. cache_escript_files() ->
  94. {ok, Files} = escript:foldl(fun(Name, _, GetBin, Acc) -> [{Name, GetBin()} | Acc] end,
  95. [], escript:script_name()),
  96. erlang:put(escript_files, Files).
  97. template_id() ->
  98. case rebar_config:get_global(template, undefined) of
  99. undefined ->
  100. ?ABORT("No template specified.\n", []);
  101. TemplateId ->
  102. TemplateId
  103. end.
  104. find_escript_templates() ->
  105. [{escript, Name} || {Name, _Bin} <- erlang:get(escript_files),
  106. re:run(Name, ?TEMPLATE_RE, [{capture, none}]) == match].
  107. find_disk_templates() ->
  108. Files = rebar_utils:find_files(filename:join(os:getenv("HOME"), ".rebar/templates"), ?TEMPLATE_RE),
  109. [{file, F} || F <- Files].
  110. select_template([], Template) ->
  111. ?ABORT("Template ~s not found.\n", [Template]);
  112. select_template([{Type, Avail} | Rest], Template) ->
  113. case filename:basename(Avail, ".template") == Template of
  114. true ->
  115. {Type, Avail};
  116. false ->
  117. select_template(Rest, Template)
  118. end.
  119. %%
  120. %% Read the contents of a file from the appropriate source
  121. %%
  122. load_file(escript, Name) ->
  123. {Name, Bin} = lists:keyfind(Name, 1, erlang:get(escript_files)),
  124. Bin;
  125. load_file(file, Name) ->
  126. {ok, Bin} = file:read_file(Name),
  127. Bin.
  128. %%
  129. %% Parse/validate variables out from the template definition
  130. %%
  131. parse_vars([], Dict) ->
  132. Dict;
  133. parse_vars([{Key, Value} | Rest], Dict) when is_atom(Key) ->
  134. parse_vars(Rest, dict:store(Key, Value, Dict));
  135. parse_vars([Other | _Rest], _Dict) ->
  136. {error, Other};
  137. parse_vars(Other, _Dict) ->
  138. {error, Other}.
  139. %%
  140. %% Given a list of keys in Dict, see if there is a corresponding value defined
  141. %% in the global config; if there is, update the key in Dict with it
  142. %%
  143. update_vars([], Dict) ->
  144. Dict;
  145. update_vars([Key | Rest], Dict) ->
  146. Value = rebar_config:get_global(Key, dict:fetch(Key, Dict)),
  147. update_vars(Rest, dict:store(Key, Value, Dict)).
  148. %%
  149. %% Given a string or binary, parse it into a list of terms, ala file:consult/0
  150. %%
  151. consult(Str) when is_list(Str) ->
  152. consult([], Str, []);
  153. consult(Bin) when is_binary(Bin)->
  154. consult([], binary_to_list(Bin), []).
  155. consult(Cont, Str, Acc) ->
  156. case erl_scan:tokens(Cont, Str, 0) of
  157. {done, Result, Remaining} ->
  158. case Result of
  159. {ok, Tokens, _} ->
  160. {ok, Term} = erl_parse:parse_term(Tokens),
  161. consult([], Remaining, [Term | Acc]);
  162. {eof, _Other} ->
  163. lists:reverse(Acc);
  164. {error, Info, _} ->
  165. {error, Info}
  166. end;
  167. {more, Cont1} ->
  168. consult(Cont1, eof, Acc)
  169. end.
  170. %%
  171. %% Render a binary to a string, using mustache and the specified context
  172. %%
  173. render(Bin, Context) ->
  174. %% Be sure to escape any double-quotes before rendering...
  175. Str = re:replace(Bin, "\"", "\\\\\"", [global, {return,list}]),
  176. mustache:render(Str, Context).
  177. %%
  178. %% Execute each instruction in a template definition file.
  179. %%
  180. execute_template([], _TemplateType, _TemplateName, _Context, _Force, ExistingFiles) ->
  181. case length(ExistingFiles) of
  182. 0 ->
  183. ok;
  184. _ ->
  185. Msg = lists:flatten([io_lib:format("\t* ~p~n", [F]) || F <- lists:reverse(ExistingFiles)]),
  186. Help = "To force overwriting, specify force=1 on the command line.\n",
  187. ?ERROR("One or more files already exist on disk and were not generated:~n~s~s", [Msg , Help])
  188. end;
  189. execute_template([{file, Input, Output} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  190. % determine if the target file already exists
  191. FileExists = filelib:is_file(Output),
  192. % perform the function if we're allowed, otherwise just process the next template
  193. if
  194. Force =:= "1"; FileExists =:= false ->
  195. InputName = filename:join(filename:dirname(TemplateName), Input),
  196. filelib:ensure_dir(Output),
  197. if
  198. {Force, FileExists} =:= {"1", true} ->
  199. ?CONSOLE("Writing ~s (forcibly overwriting)~n", [Output]);
  200. true ->
  201. ?CONSOLE("Writing ~s~n", [Output])
  202. end,
  203. case file:write_file(Output, render(load_file(TemplateType, InputName), Context)) of
  204. ok ->
  205. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles);
  206. {error, Reason} ->
  207. ?ABORT("Failed to write output file ~p: ~p\n", [Output, Reason])
  208. end;
  209. true ->
  210. execute_template(Rest, TemplateType, TemplateName, Context, Force, [Output|ExistingFiles])
  211. end;
  212. execute_template([{dir, Name} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  213. case filelib:ensure_dir(filename:join(Name, "dummy")) of
  214. ok ->
  215. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles);
  216. {error, Reason} ->
  217. ?ABORT("Failed while processing template instruction {dir, ~s}: ~p\n",
  218. [Name, Reason])
  219. end;
  220. execute_template([{variables, _} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  221. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles);
  222. execute_template([Other | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  223. ?WARN("Skipping unknown template instruction: ~p\n", [Other]),
  224. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles).