Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

278 rader
12 KiB

14 år sedan
14 år sedan
  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. %%
  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_base_compiler).
  28. -include("rebar.hrl").
  29. -export([run/4,
  30. run/7,
  31. run/8,
  32. ok_tuple/2,
  33. error_tuple/4,
  34. report/1,
  35. maybe_report/1,
  36. format_error_source/2]).
  37. -type desc() :: term().
  38. -type loc() :: {line(), col()} | line().
  39. -type line() :: integer().
  40. -type col() :: integer().
  41. -type err_or_warn() :: {module(), desc()} | {loc(), module(), desc()}.
  42. -type compile_fn_ret() :: ok | {ok, [string()]} | skipped | term().
  43. -type compile_fn() :: fun((file:filename(), [{_,_}] | rebar_dict()) -> compile_fn_ret()).
  44. -type compile_fn3() :: fun((file:filename(), file:filename(), [{_,_}] | rebar_dict())
  45. -> compile_fn_ret()).
  46. -type error_tuple() :: {error, [string()], [string()]}.
  47. -export_type([compile_fn/0, compile_fn_ret/0, error_tuple/0]).
  48. %% ===================================================================
  49. %% Public API
  50. %% ===================================================================
  51. %% @doc Runs a compile job, applying `compile_fn()' to all files,
  52. %% starting with `First' files, and then `RestFiles'.
  53. -spec run(rebar_dict() | [{_,_}] , [First], [Next], compile_fn()) ->
  54. compile_fn_ret() when
  55. First :: file:filename(),
  56. Next :: file:filename().
  57. run(Config, FirstFiles, RestFiles, CompileFn) ->
  58. %% Compile the first files in sequence
  59. compile_each(FirstFiles++RestFiles, Config, CompileFn).
  60. %% @doc Runs a compile job, applying `compile_fn3()' to all files,
  61. %% starting with `First' files, and then the other content of `SourceDir'.
  62. %% Files looked for are those ending in `SourceExt'. Results of the
  63. %% compilation are put in `TargetDir' with the base file names
  64. %% postfixed with `SourceExt'.
  65. -spec run(rebar_dict() | [{_,_}] , [First], SourceDir, SourceExt,
  66. TargetDir, TargetExt, compile_fn3()) -> compile_fn_ret() when
  67. First :: file:filename(),
  68. SourceDir :: file:filename(),
  69. TargetDir :: file:filename(),
  70. SourceExt :: string(),
  71. TargetExt :: string().
  72. run(Config, FirstFiles, SourceDir, SourceExt, TargetDir, TargetExt,
  73. Compile3Fn) ->
  74. run(Config, FirstFiles, SourceDir, SourceExt, TargetDir, TargetExt,
  75. Compile3Fn, [check_last_mod]).
  76. %% @doc Runs a compile job, applying `compile_fn3()' to all files,
  77. %% starting with `First' files, and then the other content of `SourceDir'.
  78. %% Files looked for are those ending in `SourceExt'. Results of the
  79. %% compilation are put in `TargetDir' with the base file names
  80. %% postfixed with `SourceExt'.
  81. %% Additional compile options can be passed in the last argument as
  82. %% a proplist.
  83. -spec run(rebar_dict() | [{_,_}] , [First], SourceDir, SourceExt,
  84. TargetDir, TargetExt, compile_fn3(), [term()]) -> compile_fn_ret() when
  85. First :: file:filename(),
  86. SourceDir :: file:filename(),
  87. TargetDir :: file:filename(),
  88. SourceExt :: string(),
  89. TargetExt :: string().
  90. run(Config, FirstFiles, SourceDir, SourceExt, TargetDir, TargetExt,
  91. Compile3Fn, Opts) ->
  92. %% Convert simple extension to proper regex
  93. SourceExtRe = "^(?!\\._).*\\" ++ SourceExt ++ [$$],
  94. Recursive = proplists:get_value(recursive, Opts, true),
  95. %% Find all possible source files
  96. FoundFiles = rebar_utils:find_files(SourceDir, SourceExtRe, Recursive),
  97. %% Remove first files from found files
  98. RestFiles = [Source || Source <- FoundFiles,
  99. not lists:member(Source, FirstFiles)],
  100. %% Check opts for flag indicating that compile should check lastmod
  101. CheckLastMod = proplists:get_bool(check_last_mod, Opts),
  102. run(Config, FirstFiles, RestFiles,
  103. fun(S, C) ->
  104. Target = target_file(S, SourceExt,
  105. TargetDir, TargetExt),
  106. simple_compile_wrapper(S, Target, Compile3Fn, C, CheckLastMod)
  107. end).
  108. %% @doc Format good compiler results with warnings to work with
  109. %% module internals. Assumes that warnings are not treated as errors.
  110. -spec ok_tuple(file:filename(), [string()]) -> {ok, [string()]}.
  111. ok_tuple(Source, Ws) ->
  112. {ok, format_warnings(Source, Ws)}.
  113. %% @doc format error and warning strings for a given source file
  114. %% according to user preferences.
  115. -spec error_tuple(file:filename(), [Err], [Warn], rebar_dict() | [{_,_}]) ->
  116. error_tuple() when
  117. Err :: string(),
  118. Warn :: string().
  119. error_tuple(Source, Es, Ws, Opts) ->
  120. {error, format_errors(Source, Es),
  121. format_warnings(Source, Ws, Opts)}.
  122. %% @doc from a given path, and based on the user-provided options,
  123. %% format the file path according to the preferences.
  124. -spec format_error_source(file:filename(), rebar_dict() | [{_,_}]) ->
  125. file:filename().
  126. format_error_source(Path, Opts) ->
  127. rebar_dir:format_source_file_name(Path, Opts).
  128. %% ===================================================================
  129. %% Internal functions
  130. %% ===================================================================
  131. %% @private if a check for last modifications is required, do the verification
  132. %% and possibly skip the compile job.
  133. -spec simple_compile_wrapper(Source, Target, compile_fn3(), [{_,_}] | rebar_dict(), boolean()) -> compile_fn_ret() when
  134. Source :: file:filename(),
  135. Target :: file:filename().
  136. simple_compile_wrapper(Source, Target, Compile3Fn, Config, false) ->
  137. Compile3Fn(Source, Target, Config);
  138. simple_compile_wrapper(Source, Target, Compile3Fn, Config, true) ->
  139. case filelib:last_modified(Target) < filelib:last_modified(Source) of
  140. true ->
  141. Compile3Fn(Source, Target, Config);
  142. false ->
  143. skipped
  144. end.
  145. %% @private take a basic source set of file fragments and a target location,
  146. %% create a file path and name for a compile artifact.
  147. -spec target_file(SourceFile, SourceExt, TargetDir, TargetExt) -> File when
  148. SourceFile :: file:filename(),
  149. TargetDir :: file:filename(),
  150. SourceExt :: string(),
  151. TargetExt :: string(),
  152. File :: file:filename().
  153. target_file(SourceFile, SourceExt, TargetDir, TargetExt) ->
  154. %% BaseFile = remove_common_path(SourceFile, SourceDir),
  155. filename:join([TargetDir, filename:basename(SourceFile, SourceExt) ++ TargetExt]).
  156. %% @private runs the compile function `CompileFn' on every file
  157. %% passed internally, along with the related project configuration.
  158. %% If any errors are encountered, they're reported to stdout.
  159. -spec compile_each([file:filename()], Config, CompileFn) -> Ret | no_return() when
  160. Config :: [{_,_}] | rebar_dict(),
  161. CompileFn :: compile_fn(),
  162. Ret :: compile_fn_ret().
  163. compile_each([], _Config, _CompileFn) ->
  164. ok;
  165. compile_each([Source | Rest], Config, CompileFn) ->
  166. case CompileFn(Source, Config) of
  167. ok ->
  168. ?DEBUG("~tsCompiled ~ts", [rebar_utils:indent(1), filename:basename(Source)]);
  169. {ok, Warnings} ->
  170. report(Warnings),
  171. ?DEBUG("~tsCompiled ~ts", [rebar_utils:indent(1), filename:basename(Source)]);
  172. skipped ->
  173. ?DEBUG("~tsSkipped ~ts", [rebar_utils:indent(1), filename:basename(Source)]);
  174. Error ->
  175. NewSource = format_error_source(Source, Config),
  176. ?ERROR("Compiling ~ts failed", [NewSource]),
  177. maybe_report(Error),
  178. ?DEBUG("Compilation failed: ~p", [Error]),
  179. ?FAIL
  180. end,
  181. compile_each(Rest, Config, CompileFn).
  182. %% @private Formats and returns errors ready to be output.
  183. -spec format_errors(string(), [err_or_warn()]) -> [string()].
  184. format_errors(Source, Errors) ->
  185. format_errors(Source, "", Errors).
  186. %% @private Formats and returns warning strings ready to be output.
  187. -spec format_warnings(string(), [err_or_warn()]) -> [string()].
  188. format_warnings(Source, Warnings) ->
  189. format_warnings(Source, Warnings, []).
  190. %% @private Formats and returns warnings; chooses the distinct format they
  191. %% may have based on whether `warnings_as_errors' option is on.
  192. -spec format_warnings(string(), [err_or_warn()], rebar_dict() | [{_,_}]) -> [string()].
  193. format_warnings(Source, Warnings, Opts) ->
  194. %% `Opts' can be passed in both as a list or a dictionary depending
  195. %% on whether the first call to rebar_erlc_compiler was done with
  196. %% the type `rebar_dict()' or `rebar_state:t()'.
  197. LookupFn = if is_list(Opts) -> fun lists:member/2
  198. ; true -> fun dict:is_key/2
  199. end,
  200. Prefix = case LookupFn(warnings_as_errors, Opts) of
  201. true -> "";
  202. false -> "Warning: "
  203. end,
  204. format_errors(Source, Prefix, Warnings).
  205. %% @private output compiler errors if they're judged to be reportable.
  206. -spec maybe_report(Reportable | term()) -> ok when
  207. Reportable :: {{error, error_tuple()}, Source} | error_tuple() | ErrProps,
  208. ErrProps :: [{error, string()} | Source, ...],
  209. Source :: {source, string()}.
  210. maybe_report({{error, {error, _Es, _Ws}=ErrorsAndWarnings}, {source, _}}) ->
  211. maybe_report(ErrorsAndWarnings);
  212. maybe_report([{error, E}, {source, S}]) ->
  213. report(["unexpected error compiling " ++ S, io_lib:fwrite("~n~p", [E])]);
  214. maybe_report({error, Es, Ws}) ->
  215. report(Es),
  216. report(Ws);
  217. maybe_report(_) ->
  218. ok.
  219. %% @private Outputs a bunch of strings, including a newline
  220. -spec report([string()]) -> ok.
  221. report(Messages) ->
  222. lists:foreach(fun(Msg) -> io:format("~ts~n", [Msg]) end, Messages).
  223. %% private format compiler errors into proper outputtable strings
  224. -spec format_errors(_, Extra, [err_or_warn()]) -> [string()] when
  225. Extra :: string().
  226. format_errors(_MainSource, Extra, Errors) ->
  227. [[format_error(Source, Extra, Desc) || Desc <- Descs]
  228. || {Source, Descs} <- Errors].
  229. %% @private format compiler errors into proper outputtable strings
  230. -spec format_error(file:filename(), Extra, err_or_warn()) -> string() when
  231. Extra :: string().
  232. format_error(Source, Extra, {Line, Mod=epp, Desc={include,lib,File}}) ->
  233. %% Special case for include file errors, overtaking the default one
  234. BaseDesc = Mod:format_error(Desc),
  235. Friendly = case filename:split(File) of
  236. [Lib, "include", _] ->
  237. io_lib:format("; Make sure ~s is in your app "
  238. "file's 'applications' list", [Lib]);
  239. _ ->
  240. ""
  241. end,
  242. FriendlyDesc = BaseDesc ++ Friendly,
  243. ?FMT("~ts:~w: ~ts~ts~n", [Source, Line, Extra, FriendlyDesc]);
  244. format_error(Source, Extra, {{Line, Column}, Mod, Desc}) ->
  245. ErrorDesc = Mod:format_error(Desc),
  246. ?FMT("~ts:~w:~w: ~ts~ts~n", [Source, Line, Column, Extra, ErrorDesc]);
  247. format_error(Source, Extra, {Line, Mod, Desc}) ->
  248. ErrorDesc = Mod:format_error(Desc),
  249. ?FMT("~ts:~w: ~ts~ts~n", [Source, Line, Extra, ErrorDesc]);
  250. format_error(Source, Extra, {Mod, Desc}) ->
  251. ErrorDesc = Mod:format_error(Desc),
  252. ?FMT("~ts: ~ts~ts~n", [Source, Extra, ErrorDesc]).