25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

347 satır
13 KiB

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