Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

266 rindas
10 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. HomeFiles = rebar_utils:find_files(filename:join(os:getenv("HOME"), ".rebar/templates"), ?TEMPLATE_RE),
  109. LocalFiles = rebar_utils:find_files(".", ?TEMPLATE_RE),
  110. [{file, F} || F <- HomeFiles++LocalFiles].
  111. select_template([], Template) ->
  112. ?ABORT("Template ~s not found.\n", [Template]);
  113. select_template([{Type, Avail} | Rest], Template) ->
  114. case filename:basename(Avail, ".template") == Template of
  115. true ->
  116. {Type, Avail};
  117. false ->
  118. select_template(Rest, Template)
  119. end.
  120. %%
  121. %% Read the contents of a file from the appropriate source
  122. %%
  123. load_file(escript, Name) ->
  124. {Name, Bin} = lists:keyfind(Name, 1, erlang:get(escript_files)),
  125. Bin;
  126. load_file(file, Name) ->
  127. {ok, Bin} = file:read_file(Name),
  128. Bin.
  129. %%
  130. %% Parse/validate variables out from the template definition
  131. %%
  132. parse_vars([], Dict) ->
  133. Dict;
  134. parse_vars([{Key, Value} | Rest], Dict) when is_atom(Key) ->
  135. parse_vars(Rest, dict:store(Key, Value, Dict));
  136. parse_vars([Other | _Rest], _Dict) ->
  137. {error, Other};
  138. parse_vars(Other, _Dict) ->
  139. {error, Other}.
  140. %%
  141. %% Given a list of keys in Dict, see if there is a corresponding value defined
  142. %% in the global config; if there is, update the key in Dict with it
  143. %%
  144. update_vars([], Dict) ->
  145. Dict;
  146. update_vars([Key | Rest], Dict) ->
  147. Value = rebar_config:get_global(Key, dict:fetch(Key, Dict)),
  148. update_vars(Rest, dict:store(Key, Value, Dict)).
  149. %%
  150. %% Given a string or binary, parse it into a list of terms, ala file:consult/0
  151. %%
  152. consult(Str) when is_list(Str) ->
  153. consult([], Str, []);
  154. consult(Bin) when is_binary(Bin)->
  155. consult([], binary_to_list(Bin), []).
  156. consult(Cont, Str, Acc) ->
  157. case erl_scan:tokens(Cont, Str, 0) of
  158. {done, Result, Remaining} ->
  159. case Result of
  160. {ok, Tokens, _} ->
  161. {ok, Term} = erl_parse:parse_term(Tokens),
  162. consult([], Remaining, [Term | Acc]);
  163. {eof, _Other} ->
  164. lists:reverse(Acc);
  165. {error, Info, _} ->
  166. {error, Info}
  167. end;
  168. {more, Cont1} ->
  169. consult(Cont1, eof, Acc)
  170. end.
  171. %%
  172. %% Render a binary to a string, using mustache and the specified context
  173. %%
  174. render(Bin, Context) ->
  175. %% Be sure to escape any double-quotes before rendering...
  176. Str = re:replace(Bin, "\"", "\\\\\"", [global, {return,list}]),
  177. mustache:render(Str, Context).
  178. %%
  179. %% Execute each instruction in a template definition file.
  180. %%
  181. execute_template([], _TemplateType, _TemplateName, _Context, _Force, ExistingFiles) ->
  182. case length(ExistingFiles) of
  183. 0 ->
  184. ok;
  185. _ ->
  186. Msg = lists:flatten([io_lib:format("\t* ~p~n", [F]) || F <- lists:reverse(ExistingFiles)]),
  187. Help = "To force overwriting, specify force=1 on the command line.\n",
  188. ?ERROR("One or more files already exist on disk and were not generated:~n~s~s", [Msg , Help])
  189. end;
  190. execute_template([{file, Input, Output, Render} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  191. % determine if the target file already exists
  192. FileExists = filelib:is_file(Output),
  193. % perform the function if we're allowed, otherwise just process the next template
  194. if
  195. Force =:= "1"; FileExists =:= false ->
  196. InputName = filename:join(filename:dirname(TemplateName), Input),
  197. filelib:ensure_dir(Output),
  198. if
  199. {Force, FileExists} =:= {"1", true} ->
  200. ?CONSOLE("Writing ~s (forcibly overwriting)~n", [Output]);
  201. true ->
  202. ?CONSOLE("Writing ~s~n", [Output])
  203. end,
  204. Rendered = if Render -> render(load_file(TemplateType, InputName), Context);
  205. true -> load_file(TemplateType, InputName)
  206. end,
  207. case file:write_file(Output, Rendered) of
  208. ok ->
  209. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles);
  210. {error, Reason} ->
  211. ?ABORT("Failed to write output file ~p: ~p\n", [Output, Reason])
  212. end;
  213. true ->
  214. execute_template(Rest, TemplateType, TemplateName, Context, Force, [Output|ExistingFiles])
  215. end;
  216. execute_template([{dir, Name} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  217. case filelib:ensure_dir(filename:join(Name, "dummy")) of
  218. ok ->
  219. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles);
  220. {error, Reason} ->
  221. ?ABORT("Failed while processing template instruction {dir, ~s}: ~p\n",
  222. [Name, Reason])
  223. end;
  224. execute_template([{variables, _} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  225. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles);
  226. execute_template([{file, Input, Output} | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  227. %% old short-form of {file,_,_} is same as
  228. %% new long-form of {file,_,_,true}
  229. execute_template([{file, Input, Output, true}|Rest], TemplateType, TemplateName, Context, Force, ExistingFiles);
  230. execute_template([Other | Rest], TemplateType, TemplateName, Context, Force, ExistingFiles) ->
  231. ?WARN("Skipping unknown template instruction: ~p\n", [Other]),
  232. execute_template(Rest, TemplateType, TemplateName, Context, Force, ExistingFiles).