25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

396 lines
15 KiB

15 년 전
15 년 전
15 년 전
13 년 전
15 년 전
15 년 전
13 년 전
15 년 전
15 년 전
13 년 전
14 년 전
14 년 전
14 년 전
  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_file_utils).
  28. -export([try_consult/1,
  29. consult_config/2,
  30. format_error/1,
  31. symlink_or_copy/2,
  32. rm_rf/1,
  33. cp_r/2,
  34. mv/2,
  35. delete_each/1,
  36. write_file_if_contents_differ/2,
  37. system_tmpdir/0,
  38. system_tmpdir/1,
  39. reset_dir/1,
  40. touch/1,
  41. path_from_ancestor/2,
  42. canonical_path/1,
  43. resolve_link/1,
  44. split_dirname/1]).
  45. -include("rebar.hrl").
  46. -include_lib("providers/include/providers.hrl").
  47. -include_lib("kernel/include/file.hrl").
  48. %% ===================================================================
  49. %% Public API
  50. %% ===================================================================
  51. try_consult(File) ->
  52. case file:consult(File) of
  53. {ok, Terms} ->
  54. Terms;
  55. {error, enoent} ->
  56. [];
  57. {error, Reason} ->
  58. throw(?PRV_ERROR({bad_term_file, File, Reason}))
  59. end.
  60. -spec consult_config(rebar_state:t(), string()) -> [[tuple()]].
  61. consult_config(State, Filename) ->
  62. Fullpath = filename:join(rebar_dir:root_dir(State), Filename),
  63. ?DEBUG("Loading configuration from ~p", [Fullpath]),
  64. Config = case try_consult(Fullpath) of
  65. [T] -> T;
  66. [] -> []
  67. end,
  68. JoinedConfig = lists:flatmap(
  69. fun (SubConfig) when is_list(SubConfig) ->
  70. case lists:suffix(".config", SubConfig) of
  71. false -> consult_config(State, SubConfig ++ ".config");
  72. true -> consult_config(State, SubConfig)
  73. end;
  74. (Entry) -> [Entry]
  75. end, Config),
  76. %% Backwards compatibility
  77. [JoinedConfig].
  78. format_error({bad_term_file, AppFile, Reason}) ->
  79. io_lib:format("Error reading file ~s: ~s", [AppFile, file:format_error(Reason)]).
  80. symlink_or_copy(Source, Target) ->
  81. Link = case os:type() of
  82. {win32, _} ->
  83. Source;
  84. _ ->
  85. rebar_dir:make_relative_path(Source, Target)
  86. end,
  87. case file:make_symlink(Link, Target) of
  88. ok ->
  89. ok;
  90. {error, eexist} ->
  91. exists;
  92. {error, _} ->
  93. case os:type() of
  94. {win32, _} ->
  95. S = unicode:characters_to_list(Source),
  96. T = unicode:characters_to_list(Target),
  97. case filelib:is_dir(S) of
  98. true ->
  99. win32_symlink(S, T);
  100. false ->
  101. cp_r([S], T)
  102. end;
  103. _ ->
  104. case filelib:is_dir(Target) of
  105. true ->
  106. ok;
  107. false ->
  108. cp_r([Source], Target)
  109. end
  110. end
  111. end.
  112. win32_symlink(Source, Target) ->
  113. Res = rebar_utils:sh(
  114. ?FMT("cmd /c mklink /j \"~s\" \"~s\"",
  115. [rebar_utils:escape_double_quotes(filename:nativename(Target)),
  116. rebar_utils:escape_double_quotes(filename:nativename(Source))]),
  117. [{use_stdout, false}, return_on_error]),
  118. case win32_ok(Res) of
  119. true -> ok;
  120. false ->
  121. {error, lists:flatten(
  122. io_lib:format("Failed to symlink ~s to ~s~n",
  123. [Source, Target]))}
  124. end.
  125. %% @doc Remove files and directories.
  126. %% Target is a single filename, directoryname or wildcard expression.
  127. -spec rm_rf(string()) -> 'ok'.
  128. rm_rf(Target) ->
  129. case os:type() of
  130. {unix, _} ->
  131. EscTarget = rebar_utils:escape_chars(Target),
  132. {ok, []} = rebar_utils:sh(?FMT("rm -rf ~s", [EscTarget]),
  133. [{use_stdout, false}, abort_on_error]),
  134. ok;
  135. {win32, _} ->
  136. Filelist = filelib:wildcard(Target),
  137. Dirs = [F || F <- Filelist, filelib:is_dir(F)],
  138. Files = Filelist -- Dirs,
  139. ok = delete_each(Files),
  140. ok = delete_each_dir_win32(Dirs),
  141. ok
  142. end.
  143. -spec cp_r(list(string()), file:filename()) -> 'ok'.
  144. cp_r([], _Dest) ->
  145. ok;
  146. cp_r(Sources, Dest) ->
  147. case os:type() of
  148. {unix, _} ->
  149. EscSources = [rebar_utils:escape_chars(Src) || Src <- Sources],
  150. SourceStr = string:join(EscSources, " "),
  151. {ok, []} = rebar_utils:sh(?FMT("cp -Rp ~s \"~s\"",
  152. [SourceStr, rebar_utils:escape_double_quotes(Dest)]),
  153. [{use_stdout, false}, abort_on_error]),
  154. ok;
  155. {win32, _} ->
  156. lists:foreach(fun(Src) -> ok = cp_r_win32(Src,Dest) end, Sources),
  157. ok
  158. end.
  159. -spec mv(string(), file:filename()) -> 'ok'.
  160. mv(Source, Dest) ->
  161. case os:type() of
  162. {unix, _} ->
  163. EscSource = rebar_utils:escape_chars(Source),
  164. EscDest = rebar_utils:escape_chars(Dest),
  165. case rebar_utils:sh(?FMT("mv ~s ~s", [EscSource, EscDest]),
  166. [{use_stdout, false}, abort_on_error]) of
  167. {ok, []} ->
  168. ok;
  169. {ok, Warning} ->
  170. ?WARN("mv: ~p", [Warning]),
  171. ok
  172. end;
  173. {win32, _} ->
  174. Cmd = case filelib:is_dir(Source) of
  175. true ->
  176. ?FMT("robocopy /move /e \"~s\" \"~s\" 1> nul",
  177. [rebar_utils:escape_double_quotes(filename:nativename(Source)),
  178. rebar_utils:escape_double_quotes(filename:nativename(Dest))]);
  179. false ->
  180. ?FMT("robocopy /move /e \"~s\" \"~s\" \"~s\" 1> nul",
  181. [rebar_utils:escape_double_quotes(filename:nativename(filename:dirname(Source))),
  182. rebar_utils:escape_double_quotes(filename:nativename(Dest)),
  183. rebar_utils:escape_double_quotes(filename:basename(Source))])
  184. end,
  185. Res = rebar_utils:sh(Cmd,
  186. [{use_stdout, false}, return_on_error]),
  187. case win32_ok(Res) of
  188. true -> ok;
  189. false ->
  190. {error, lists:flatten(
  191. io_lib:format("Failed to move ~s to ~s~n",
  192. [Source, Dest]))}
  193. end
  194. end.
  195. win32_ok({ok, _}) -> true;
  196. win32_ok({error, {Rc, _}}) when Rc<9; Rc=:=16 -> true;
  197. win32_ok(_) -> false.
  198. delete_each([]) ->
  199. ok;
  200. delete_each([File | Rest]) ->
  201. case file:delete(File) of
  202. ok ->
  203. delete_each(Rest);
  204. {error, enoent} ->
  205. delete_each(Rest);
  206. {error, Reason} ->
  207. ?ERROR("Failed to delete file ~s: ~p\n", [File, Reason]),
  208. ?FAIL
  209. end.
  210. write_file_if_contents_differ(Filename, Bytes) ->
  211. ToWrite = iolist_to_binary(Bytes),
  212. case file:read_file(Filename) of
  213. {ok, ToWrite} ->
  214. ok;
  215. {ok, _} ->
  216. file:write_file(Filename, ToWrite, [raw]);
  217. {error, _} ->
  218. file:write_file(Filename, ToWrite, [raw])
  219. end.
  220. %% returns an os appropriate tmpdir given a path
  221. -spec system_tmpdir() -> file:filename().
  222. system_tmpdir() -> system_tmpdir([]).
  223. -spec system_tmpdir(PathComponents) -> file:filename() when
  224. PathComponents :: [file:name()].
  225. system_tmpdir(PathComponents) ->
  226. Tmp = case erlang:system_info(system_architecture) of
  227. "win32" ->
  228. "./tmp";
  229. _SysArch ->
  230. "/tmp"
  231. end,
  232. filename:join([Tmp|PathComponents]).
  233. %% recursively removes a directory and then recreates the same
  234. %% directory but empty
  235. -spec reset_dir(Path) -> ok | {error, Reason} when
  236. Path :: file:name(),
  237. Reason :: file:posix().
  238. reset_dir(Path) ->
  239. %% delete the directory if it exists
  240. _ = ec_file:remove(Path, [recursive]),
  241. %% recreate the directory
  242. filelib:ensure_dir(filename:join([Path, "dummy.beam"])).
  243. %% Linux touch but using erlang functions to work in bot *nix os and
  244. %% windows
  245. -spec touch(Path) -> ok | {error, Reason} when
  246. Path :: file:name(),
  247. Reason :: file:posix().
  248. touch(Path) ->
  249. {ok, A} = file:read_file_info(Path),
  250. ok = file:write_file_info(Path, A#file_info{mtime = calendar:local_time(),
  251. atime = calendar:local_time()}).
  252. %% for a given path return the path relative to a base directory
  253. -spec path_from_ancestor(string(), string()) -> {ok, string()} | {error, badparent}.
  254. path_from_ancestor(Target, To) ->
  255. path_from_ancestor_(filename:split(canonical_path(Target)),
  256. filename:split(canonical_path(To))).
  257. path_from_ancestor_([Part|Target], [Part|To]) -> path_from_ancestor_(Target, To);
  258. path_from_ancestor_([], []) -> {ok, ""};
  259. path_from_ancestor_(Target, []) -> {ok, filename:join(Target)};
  260. path_from_ancestor_(_, _) -> {error, badparent}.
  261. %% reduce a filepath by removing all incidences of `.' and `..'
  262. -spec canonical_path(string()) -> string().
  263. canonical_path(Dir) ->
  264. Canon = canonical_path([], filename:split(filename:absname(Dir))),
  265. filename:nativename(Canon).
  266. canonical_path([], []) -> filename:absname("/");
  267. canonical_path(Acc, []) -> filename:join(lists:reverse(Acc));
  268. canonical_path(Acc, ["."|Rest]) -> canonical_path(Acc, Rest);
  269. canonical_path([_|Acc], [".."|Rest]) -> canonical_path(Acc, Rest);
  270. canonical_path([], [".."|Rest]) -> canonical_path([], Rest);
  271. canonical_path(Acc, [Component|Rest]) -> canonical_path([Component|Acc], Rest).
  272. %% @doc returns canonical target of path if path is a link, otherwise returns path
  273. -spec resolve_link(string()) -> string().
  274. resolve_link(Path) ->
  275. case file:read_link(Path) of
  276. {ok, Target} ->
  277. canonical_path(filename:absname(Target, filename:dirname(Path)));
  278. {error, _} -> Path
  279. end.
  280. %% @doc splits a path into dirname and basename
  281. -spec split_dirname(string()) -> {string(), string()}.
  282. split_dirname(Path) ->
  283. {filename:dirname(Path), filename:basename(Path)}.
  284. %% ===================================================================
  285. %% Internal functions
  286. %% ===================================================================
  287. delete_each_dir_win32([]) -> ok;
  288. delete_each_dir_win32([Dir | Rest]) ->
  289. {ok, []} = rebar_utils:sh(?FMT("rd /q /s \"~s\"",
  290. [rebar_utils:escape_double_quotes(filename:nativename(Dir))]),
  291. [{use_stdout, false}, return_on_error]),
  292. delete_each_dir_win32(Rest).
  293. xcopy_win32(Source,Dest)->
  294. %% "xcopy \"~s\" \"~s\" /q /y /e 2> nul", Changed to robocopy to
  295. %% handle long names. May have issues with older windows.
  296. Cmd = case filelib:is_dir(Source) of
  297. true ->
  298. %% For robocopy, copying /a/b/c/ to /d/e/f/ recursively does not
  299. %% create /d/e/f/c/*, but rather copies all files to /d/e/f/*.
  300. %% The usage we make here expects the former, not the later, so we
  301. %% must manually add the last fragment of a directory to the `Dest`
  302. %% in order to properly replicate POSIX platforms
  303. NewDest = filename:join([Dest, filename:basename(Source)]),
  304. ?FMT("robocopy \"~s\" \"~s\" /e /is 1> nul",
  305. [rebar_utils:escape_double_quotes(filename:nativename(Source)),
  306. rebar_utils:escape_double_quotes(filename:nativename(NewDest))]);
  307. false ->
  308. ?FMT("robocopy \"~s\" \"~s\" \"~s\" /e /is 1> nul",
  309. [rebar_utils:escape_double_quotes(filename:nativename(filename:dirname(Source))),
  310. rebar_utils:escape_double_quotes(filename:nativename(Dest)),
  311. rebar_utils:escape_double_quotes(filename:basename(Source))])
  312. end,
  313. Res = rebar_utils:sh(Cmd,
  314. [{use_stdout, false}, return_on_error]),
  315. case win32_ok(Res) of
  316. true -> ok;
  317. false ->
  318. {error, lists:flatten(
  319. io_lib:format("Failed to copy ~s to ~s~n",
  320. [Source, Dest]))}
  321. end.
  322. cp_r_win32({true, SourceDir}, {true, DestDir}) ->
  323. %% from directory to directory
  324. ok = case file:make_dir(DestDir) of
  325. {error, eexist} -> ok;
  326. Other -> Other
  327. end,
  328. ok = xcopy_win32(SourceDir, DestDir);
  329. cp_r_win32({false, Source} = S,{true, DestDir}) ->
  330. %% from file to directory
  331. cp_r_win32(S, {false, filename:join(DestDir, filename:basename(Source))});
  332. cp_r_win32({false, Source},{false, Dest}) ->
  333. %% from file to file
  334. {ok,_} = file:copy(Source, Dest),
  335. ok;
  336. cp_r_win32({true, SourceDir}, {false, DestDir}) ->
  337. case filelib:is_regular(DestDir) of
  338. true ->
  339. %% From directory to file? This shouldn't happen
  340. {error, lists:flatten(
  341. io_lib:format("Cannot copy dir (~p) to file (~p)\n",
  342. [SourceDir, DestDir]))};
  343. false ->
  344. %% Specifying a target directory that doesn't currently exist.
  345. %% So let's attempt to create this directory
  346. case filelib:ensure_dir(filename:join(DestDir, "dummy")) of
  347. ok ->
  348. ok = xcopy_win32(SourceDir, DestDir);
  349. {error, Reason} ->
  350. {error, lists:flatten(
  351. io_lib:format("Unable to create dir ~p: ~p\n",
  352. [DestDir, Reason]))}
  353. end
  354. end;
  355. cp_r_win32(Source,Dest) ->
  356. Dst = {filelib:is_dir(Dest), Dest},
  357. lists:foreach(fun(Src) ->
  358. ok = cp_r_win32({filelib:is_dir(Src), Src}, Dst)
  359. end, filelib:wildcard(Source)),
  360. ok.