Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

513 wiersze
20 KiB

15 lat temu
15 lat temu
15 lat temu
12 lat temu
15 lat temu
15 lat temu
12 lat temu
15 lat temu
15 lat temu
12 lat temu
14 lat temu
14 lat temu
14 lat temu
  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. %% since consult_config returns a list in a list we take the head here
  72. false -> hd(consult_config(State, SubConfig ++ ".config"));
  73. true -> hd(consult_config(State, SubConfig))
  74. end;
  75. (Entry) -> [Entry]
  76. end, Config),
  77. %% Backwards compatibility
  78. [JoinedConfig].
  79. format_error({bad_term_file, AppFile, Reason}) ->
  80. io_lib:format("Error reading file ~ts: ~ts", [AppFile, file:format_error(Reason)]).
  81. symlink_or_copy(Source, Target) ->
  82. Link = case os:type() of
  83. {win32, _} ->
  84. Source;
  85. _ ->
  86. rebar_dir:make_relative_path(Source, Target)
  87. end,
  88. case file:make_symlink(Link, Target) of
  89. ok ->
  90. ok;
  91. {error, eexist} ->
  92. exists;
  93. {error, _} ->
  94. case os:type() of
  95. {win32, _} ->
  96. S = unicode:characters_to_list(Source),
  97. T = unicode:characters_to_list(Target),
  98. case filelib:is_dir(S) of
  99. true ->
  100. win32_symlink_or_copy(S, T);
  101. false ->
  102. cp_r([S], T)
  103. end;
  104. _ ->
  105. case filelib:is_dir(Target) of
  106. true ->
  107. ok;
  108. false ->
  109. cp_r([Source], Target)
  110. end
  111. end
  112. end.
  113. %% @private Compatibility function for windows
  114. win32_symlink_or_copy(Source, Target) ->
  115. Res = rebar_utils:sh(
  116. ?FMT("cmd /c mklink /j \"~ts\" \"~ts\"",
  117. [rebar_utils:escape_double_quotes(filename:nativename(Target)),
  118. rebar_utils:escape_double_quotes(filename:nativename(Source))]),
  119. [{use_stdout, false}, return_on_error]),
  120. case win32_mklink_ok(Res, Target) of
  121. true -> ok;
  122. false -> cp_r_win32(Source, drop_last_dir_from_path(Target))
  123. end.
  124. %% @private specifically pattern match against the output
  125. %% of the windows 'mklink' shell call; different values from
  126. %% what win32_ok/1 handles
  127. win32_mklink_ok({ok, _}, _) ->
  128. true;
  129. win32_mklink_ok({error,{1,"Local NTFS volumes are required to complete the operation.\n"}}, _) ->
  130. false;
  131. win32_mklink_ok({error,{1,"Cannot create a file when that file already exists.\n"}}, Target) ->
  132. % File or dir is already in place; find if it is already a symlink (true) or
  133. % if it is a directory (copy-required; false)
  134. is_symlink(Target);
  135. win32_mklink_ok(_, _) ->
  136. false.
  137. %% @private
  138. is_symlink(Filename) ->
  139. {ok, Info} = file:read_link_info(Filename),
  140. Info#file_info.type == symlink.
  141. %% @private
  142. %% drops the last 'node' of the filename, presumably the last dir such as 'src'
  143. %% this is because cp_r_win32/2 automatically adds the dir name, to appease
  144. %% robocopy and be more uniform with POSIX
  145. drop_last_dir_from_path([]) ->
  146. [];
  147. drop_last_dir_from_path(Path) ->
  148. case lists:droplast(filename:split(Path)) of
  149. [] -> [];
  150. Dirs -> filename:join(Dirs)
  151. end.
  152. %% @doc Remove files and directories.
  153. %% Target is a single filename, directoryname or wildcard expression.
  154. -spec rm_rf(string()) -> 'ok'.
  155. rm_rf(Target) ->
  156. case os:type() of
  157. {unix, _} ->
  158. EscTarget = rebar_utils:escape_chars(Target),
  159. {ok, []} = rebar_utils:sh(?FMT("rm -rf ~ts", [EscTarget]),
  160. [{use_stdout, false}, abort_on_error]),
  161. ok;
  162. {win32, _} ->
  163. Filelist = filelib:wildcard(Target),
  164. Dirs = [F || F <- Filelist, filelib:is_dir(F)],
  165. Files = Filelist -- Dirs,
  166. ok = delete_each(Files),
  167. ok = delete_each_dir_win32(Dirs),
  168. ok
  169. end.
  170. -spec cp_r(list(string()), file:filename()) -> 'ok'.
  171. cp_r([], _Dest) ->
  172. ok;
  173. cp_r(Sources, Dest) ->
  174. case os:type() of
  175. {unix, _} ->
  176. EscSources = [rebar_utils:escape_chars(Src) || Src <- Sources],
  177. SourceStr = string:join(EscSources, " "),
  178. {ok, []} = rebar_utils:sh(?FMT("cp -Rp ~ts \"~ts\"",
  179. [SourceStr, rebar_utils:escape_double_quotes(Dest)]),
  180. [{use_stdout, false}, abort_on_error]),
  181. ok;
  182. {win32, _} ->
  183. lists:foreach(fun(Src) -> ok = cp_r_win32(Src,Dest) end, Sources),
  184. ok
  185. end.
  186. -spec mv(string(), file:filename()) -> 'ok'.
  187. mv(Source, Dest) ->
  188. case os:type() of
  189. {unix, _} ->
  190. EscSource = rebar_utils:escape_chars(Source),
  191. EscDest = rebar_utils:escape_chars(Dest),
  192. case rebar_utils:sh(?FMT("mv ~ts ~ts", [EscSource, EscDest]),
  193. [{use_stdout, false}, abort_on_error]) of
  194. {ok, []} ->
  195. ok;
  196. {ok, Warning} ->
  197. ?WARN("mv: ~p", [Warning]),
  198. ok
  199. end;
  200. {win32, _} ->
  201. case filelib:is_dir(Source) of
  202. true ->
  203. SrcDir = filename:nativename(Source),
  204. DestDir = case filelib:is_dir(Dest) of
  205. true ->
  206. %% to simulate unix/posix mv, we have to replicate
  207. %% the same directory movement by moving the whole
  208. %% top-level directory, not just the insides
  209. SrcName = filename:basename(Source),
  210. filename:nativename(filename:join(Dest, SrcName));
  211. false ->
  212. filename:nativename(Dest)
  213. end,
  214. robocopy_dir(SrcDir, DestDir);
  215. false ->
  216. SrcDir = filename:nativename(filename:dirname(Source)),
  217. SrcName = filename:basename(Source),
  218. DestDir = filename:nativename(filename:dirname(Dest)),
  219. DestName = filename:basename(Dest),
  220. IsDestDir = filelib:is_dir(Dest),
  221. if IsDestDir ->
  222. %% if basename and target name are different because
  223. %% we move to a directory, then just move there.
  224. %% Similarly, if they are the same but we're going to
  225. %% a directory, let's just do that directly.
  226. FullDestDir = filename:nativename(Dest),
  227. robocopy_file(SrcDir, FullDestDir, SrcName)
  228. ; SrcName =:= DestName ->
  229. %% if basename and target name are the same and both are files,
  230. %% we do a regular move with robocopy without rename.
  231. robocopy_file(SrcDir, DestDir, DestName)
  232. ; SrcName =/= DestName->
  233. robocopy_mv_and_rename(Source, Dest, SrcDir, SrcName, DestDir, DestName)
  234. end
  235. end
  236. end.
  237. robocopy_mv_and_rename(Source, Dest, SrcDir, SrcName, DestDir, DestName) ->
  238. %% If we're moving a file and the origin and
  239. %% destination names are different:
  240. %% - mktmp
  241. %% - robocopy source_dir tmp_dir srcname
  242. %% - rename srcname destname (to avoid clobbering)
  243. %% - robocopy tmp_dir dest_dir destname
  244. %% - remove tmp_dir
  245. case ec_file:insecure_mkdtemp() of
  246. {error, _Reason} ->
  247. {error, lists:flatten(
  248. io_lib:format("Failed to move ~ts to ~ts (tmpdir failed)~n",
  249. [Source, Dest]))};
  250. TmpPath ->
  251. case robocopy_file(SrcDir, TmpPath, SrcName) of
  252. {error, Reason} ->
  253. {error, Reason};
  254. ok ->
  255. TmpSrc = filename:join(TmpPath, SrcName),
  256. TmpDst = filename:join(TmpPath, DestName),
  257. case file:rename(TmpSrc, TmpDst) of
  258. {error, _} ->
  259. {error, lists:flatten(
  260. io_lib:format("Failed to move ~ts to ~ts (via rename)~n",
  261. [Source, Dest]))};
  262. ok ->
  263. case robocopy_file(TmpPath, DestDir, DestName) of
  264. Err = {error, _} -> Err;
  265. OK -> rm_rf(TmpPath), OK
  266. end
  267. end
  268. end
  269. end.
  270. robocopy_file(SrcPath, DestPath, FileName) ->
  271. Cmd = ?FMT("robocopy /move /e \"~ts\" \"~ts\" \"~ts\"",
  272. [rebar_utils:escape_double_quotes(SrcPath),
  273. rebar_utils:escape_double_quotes(DestPath),
  274. rebar_utils:escape_double_quotes(FileName)]),
  275. Res = rebar_utils:sh(Cmd, [{use_stdout, false}, return_on_error]),
  276. case win32_ok(Res) of
  277. false ->
  278. {error, lists:flatten(
  279. io_lib:format("Failed to move ~ts to ~ts~n",
  280. [filename:join(SrcPath, FileName),
  281. filename:join(DestPath, FileName)]))};
  282. true ->
  283. ok
  284. end.
  285. robocopy_dir(Source, Dest) ->
  286. Cmd = ?FMT("robocopy /move /e \"~ts\" \"~ts\"",
  287. [rebar_utils:escape_double_quotes(Source),
  288. rebar_utils:escape_double_quotes(Dest)]),
  289. Res = rebar_utils:sh(Cmd,
  290. [{use_stdout, false}, return_on_error]),
  291. case win32_ok(Res) of
  292. true -> ok;
  293. false ->
  294. {error, lists:flatten(
  295. io_lib:format("Failed to move ~ts to ~ts~n",
  296. [Source, Dest]))}
  297. end.
  298. win32_ok({ok, _}) -> true;
  299. win32_ok({error, {Rc, _}}) when Rc<9; Rc=:=16 -> true;
  300. win32_ok(_) -> false.
  301. delete_each([]) ->
  302. ok;
  303. delete_each([File | Rest]) ->
  304. case file:delete(File) of
  305. ok ->
  306. delete_each(Rest);
  307. {error, enoent} ->
  308. delete_each(Rest);
  309. {error, Reason} ->
  310. ?ERROR("Failed to delete file ~ts: ~p\n", [File, Reason]),
  311. ?FAIL
  312. end.
  313. write_file_if_contents_differ(Filename, Bytes) ->
  314. %% first try to convert directly to binaries,
  315. %% but if it fails, we likely contain unicode and
  316. %% need special treatment
  317. ToWrite = try
  318. iolist_to_binary(Bytes)
  319. catch
  320. error:badarg -> unicode:characters_to_binary(Bytes)
  321. end,
  322. case file:read_file(Filename) of
  323. {ok, ToWrite} ->
  324. ok;
  325. {ok, _} ->
  326. file:write_file(Filename, ToWrite, [raw]);
  327. {error, _} ->
  328. file:write_file(Filename, ToWrite, [raw])
  329. end.
  330. %% returns an os appropriate tmpdir given a path
  331. -spec system_tmpdir() -> file:filename().
  332. system_tmpdir() -> system_tmpdir([]).
  333. -spec system_tmpdir(PathComponents) -> file:filename() when
  334. PathComponents :: [file:name()].
  335. system_tmpdir(PathComponents) ->
  336. Tmp = case erlang:system_info(system_architecture) of
  337. "win32" ->
  338. "./tmp";
  339. _SysArch ->
  340. "/tmp"
  341. end,
  342. filename:join([Tmp|PathComponents]).
  343. %% recursively removes a directory and then recreates the same
  344. %% directory but empty
  345. -spec reset_dir(Path) -> ok | {error, Reason} when
  346. Path :: file:name(),
  347. Reason :: file:posix().
  348. reset_dir(Path) ->
  349. %% delete the directory if it exists
  350. _ = ec_file:remove(Path, [recursive]),
  351. %% recreate the directory
  352. filelib:ensure_dir(filename:join([Path, "dummy.beam"])).
  353. %% Linux touch but using erlang functions to work in bot *nix os and
  354. %% windows
  355. -spec touch(Path) -> ok | {error, Reason} when
  356. Path :: file:name(),
  357. Reason :: file:posix().
  358. touch(Path) ->
  359. {ok, A} = file:read_file_info(Path),
  360. ok = file:write_file_info(Path, A#file_info{mtime = calendar:local_time(),
  361. atime = calendar:local_time()}).
  362. %% for a given path return the path relative to a base directory
  363. -spec path_from_ancestor(string(), string()) -> {ok, string()} | {error, badparent}.
  364. path_from_ancestor(Target, To) ->
  365. path_from_ancestor_(filename:split(canonical_path(Target)),
  366. filename:split(canonical_path(To))).
  367. path_from_ancestor_([Part|Target], [Part|To]) -> path_from_ancestor_(Target, To);
  368. path_from_ancestor_([], []) -> {ok, ""};
  369. path_from_ancestor_(Target, []) -> {ok, filename:join(Target)};
  370. path_from_ancestor_(_, _) -> {error, badparent}.
  371. %% reduce a filepath by removing all incidences of `.' and `..'
  372. -spec canonical_path(string()) -> string().
  373. canonical_path(Dir) ->
  374. Canon = canonical_path([], filename:split(filename:absname(Dir))),
  375. filename:nativename(Canon).
  376. canonical_path([], []) -> filename:absname("/");
  377. canonical_path(Acc, []) -> filename:join(lists:reverse(Acc));
  378. canonical_path(Acc, ["."|Rest]) -> canonical_path(Acc, Rest);
  379. canonical_path([_|Acc], [".."|Rest]) -> canonical_path(Acc, Rest);
  380. canonical_path([], [".."|Rest]) -> canonical_path([], Rest);
  381. canonical_path(Acc, [Component|Rest]) -> canonical_path([Component|Acc], Rest).
  382. %% @doc returns canonical target of path if path is a link, otherwise returns path
  383. -spec resolve_link(string()) -> string().
  384. resolve_link(Path) ->
  385. case file:read_link(Path) of
  386. {ok, Target} ->
  387. canonical_path(filename:absname(Target, filename:dirname(Path)));
  388. {error, _} -> Path
  389. end.
  390. %% @doc splits a path into dirname and basename
  391. -spec split_dirname(string()) -> {string(), string()}.
  392. split_dirname(Path) ->
  393. {filename:dirname(Path), filename:basename(Path)}.
  394. %% ===================================================================
  395. %% Internal functions
  396. %% ===================================================================
  397. delete_each_dir_win32([]) -> ok;
  398. delete_each_dir_win32([Dir | Rest]) ->
  399. {ok, []} = rebar_utils:sh(?FMT("rd /q /s \"~ts\"",
  400. [rebar_utils:escape_double_quotes(filename:nativename(Dir))]),
  401. [{use_stdout, false}, return_on_error]),
  402. delete_each_dir_win32(Rest).
  403. xcopy_win32(Source,Dest)->
  404. %% "xcopy \"~ts\" \"~ts\" /q /y /e 2> nul", Changed to robocopy to
  405. %% handle long names. May have issues with older windows.
  406. Cmd = case filelib:is_dir(Source) of
  407. true ->
  408. %% For robocopy, copying /a/b/c/ to /d/e/f/ recursively does not
  409. %% create /d/e/f/c/*, but rather copies all files to /d/e/f/*.
  410. %% The usage we make here expects the former, not the later, so we
  411. %% must manually add the last fragment of a directory to the `Dest`
  412. %% in order to properly replicate POSIX platforms
  413. NewDest = filename:join([Dest, filename:basename(Source)]),
  414. ?FMT("robocopy \"~ts\" \"~ts\" /e /is 1> nul",
  415. [rebar_utils:escape_double_quotes(filename:nativename(Source)),
  416. rebar_utils:escape_double_quotes(filename:nativename(NewDest))]);
  417. false ->
  418. ?FMT("robocopy \"~ts\" \"~ts\" \"~ts\" /e /is 1> nul",
  419. [rebar_utils:escape_double_quotes(filename:nativename(filename:dirname(Source))),
  420. rebar_utils:escape_double_quotes(filename:nativename(Dest)),
  421. rebar_utils:escape_double_quotes(filename:basename(Source))])
  422. end,
  423. Res = rebar_utils:sh(Cmd,
  424. [{use_stdout, false}, return_on_error]),
  425. case win32_ok(Res) of
  426. true -> ok;
  427. false ->
  428. {error, lists:flatten(
  429. io_lib:format("Failed to copy ~ts to ~ts~n",
  430. [Source, Dest]))}
  431. end.
  432. cp_r_win32({true, SourceDir}, {true, DestDir}) ->
  433. %% from directory to directory
  434. ok = case file:make_dir(DestDir) of
  435. {error, eexist} -> ok;
  436. Other -> Other
  437. end,
  438. ok = xcopy_win32(SourceDir, DestDir);
  439. cp_r_win32({false, Source} = S,{true, DestDir}) ->
  440. %% from file to directory
  441. cp_r_win32(S, {false, filename:join(DestDir, filename:basename(Source))});
  442. cp_r_win32({false, Source},{false, Dest}) ->
  443. %% from file to file
  444. {ok,_} = file:copy(Source, Dest),
  445. ok;
  446. cp_r_win32({true, SourceDir}, {false, DestDir}) ->
  447. case filelib:is_regular(DestDir) of
  448. true ->
  449. %% From directory to file? This shouldn't happen
  450. {error, lists:flatten(
  451. io_lib:format("Cannot copy dir (~p) to file (~p)\n",
  452. [SourceDir, DestDir]))};
  453. false ->
  454. %% Specifying a target directory that doesn't currently exist.
  455. %% So let's attempt to create this directory
  456. case filelib:ensure_dir(filename:join(DestDir, "dummy")) of
  457. ok ->
  458. ok = xcopy_win32(SourceDir, DestDir);
  459. {error, Reason} ->
  460. {error, lists:flatten(
  461. io_lib:format("Unable to create dir ~p: ~p\n",
  462. [DestDir, Reason]))}
  463. end
  464. end;
  465. cp_r_win32(Source,Dest) ->
  466. Dst = {filelib:is_dir(Dest), Dest},
  467. lists:foreach(fun(Src) ->
  468. ok = cp_r_win32({filelib:is_dir(Src), Src}, Dst)
  469. end, filelib:wildcard(Source)),
  470. ok.