You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

539 line
21 KiB

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