No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

553 líneas
22 KiB

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