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.

538 lines
21 KiB

15 years ago
15 years ago
15 years ago
12 years ago
15 years ago
15 years ago
12 years ago
15 years ago
7 years ago
15 years ago
12 years ago
14 years ago
14 years ago
14 years ago
  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) == $/} of
  184. {true, true} ->
  185. rebar_string:trim(SourceStr, trailing, "/");
  186. {true, false} ->
  187. SourceStr;
  188. {false, _} ->
  189. SourceStr
  190. end,
  191. % ensure destination exists before copying files into it
  192. {ok, []} = rebar_utils:sh(?FMT("mkdir -p ~ts",
  193. [rebar_utils:escape_chars(Dest)]),
  194. [{use_stdout, false}, abort_on_error]),
  195. {ok, []} = rebar_utils:sh(?FMT("cp -Rp ~ts \"~ts\"",
  196. [Source, rebar_utils:escape_double_quotes(Dest)]),
  197. [{use_stdout, true}, abort_on_error]),
  198. ok;
  199. {win32, _} ->
  200. lists:foreach(fun(Src) -> ok = cp_r_win32(Src,Dest) end, Sources),
  201. ok
  202. end.
  203. -spec mv(string(), file:filename()) -> 'ok'.
  204. mv(Source, Dest) ->
  205. case os:type() of
  206. {unix, _} ->
  207. EscSource = rebar_utils:escape_chars(Source),
  208. EscDest = rebar_utils:escape_chars(Dest),
  209. case rebar_utils:sh(?FMT("mv ~ts ~ts", [EscSource, EscDest]),
  210. [{use_stdout, false}, abort_on_error]) of
  211. {ok, []} ->
  212. ok;
  213. {ok, Warning} ->
  214. ?WARN("mv: ~p", [Warning]),
  215. ok
  216. end;
  217. {win32, _} ->
  218. case filelib:is_dir(Source) of
  219. true ->
  220. SrcDir = filename:nativename(Source),
  221. DestDir = case filelib:is_dir(Dest) of
  222. true ->
  223. %% to simulate unix/posix mv, we have to replicate
  224. %% the same directory movement by moving the whole
  225. %% top-level directory, not just the insides
  226. SrcName = filename:basename(Source),
  227. filename:nativename(filename:join(Dest, SrcName));
  228. false ->
  229. filename:nativename(Dest)
  230. end,
  231. robocopy_dir(SrcDir, DestDir);
  232. false ->
  233. SrcDir = filename:nativename(filename:dirname(Source)),
  234. SrcName = filename:basename(Source),
  235. DestDir = filename:nativename(filename:dirname(Dest)),
  236. DestName = filename:basename(Dest),
  237. IsDestDir = filelib:is_dir(Dest),
  238. if IsDestDir ->
  239. %% if basename and target name are different because
  240. %% we move to a directory, then just move there.
  241. %% Similarly, if they are the same but we're going to
  242. %% a directory, let's just do that directly.
  243. FullDestDir = filename:nativename(Dest),
  244. robocopy_file(SrcDir, FullDestDir, SrcName)
  245. ; SrcName =:= DestName ->
  246. %% if basename and target name are the same and both are files,
  247. %% we do a regular move with robocopy without rename.
  248. robocopy_file(SrcDir, DestDir, DestName)
  249. ; SrcName =/= DestName->
  250. robocopy_mv_and_rename(Source, Dest, SrcDir, SrcName, DestDir, DestName)
  251. end
  252. end
  253. end.
  254. robocopy_mv_and_rename(Source, Dest, SrcDir, SrcName, DestDir, DestName) ->
  255. %% If we're moving a file and the origin and
  256. %% destination names are different:
  257. %% - mktmp
  258. %% - robocopy source_dir tmp_dir srcname
  259. %% - rename srcname destname (to avoid clobbering)
  260. %% - robocopy tmp_dir dest_dir destname
  261. %% - remove tmp_dir
  262. case ec_file:insecure_mkdtemp() of
  263. {error, _Reason} ->
  264. {error, lists:flatten(
  265. io_lib:format("Failed to move ~ts to ~ts (tmpdir failed)~n",
  266. [Source, Dest]))};
  267. TmpPath ->
  268. case robocopy_file(SrcDir, TmpPath, SrcName) of
  269. {error, Reason} ->
  270. {error, Reason};
  271. ok ->
  272. TmpSrc = filename:join(TmpPath, SrcName),
  273. TmpDst = filename:join(TmpPath, DestName),
  274. case file:rename(TmpSrc, TmpDst) of
  275. {error, _} ->
  276. {error, lists:flatten(
  277. io_lib:format("Failed to move ~ts to ~ts (via rename)~n",
  278. [Source, Dest]))};
  279. ok ->
  280. case robocopy_file(TmpPath, DestDir, DestName) of
  281. Err = {error, _} -> Err;
  282. OK -> rm_rf(TmpPath), OK
  283. end
  284. end
  285. end
  286. end.
  287. robocopy_file(SrcPath, DestPath, FileName) ->
  288. Cmd = ?FMT("robocopy /move /e \"~ts\" \"~ts\" \"~ts\"",
  289. [rebar_utils:escape_double_quotes(SrcPath),
  290. rebar_utils:escape_double_quotes(DestPath),
  291. rebar_utils:escape_double_quotes(FileName)]),
  292. Res = rebar_utils:sh(Cmd, [{use_stdout, false}, return_on_error]),
  293. case win32_ok(Res) of
  294. false ->
  295. {error, lists:flatten(
  296. io_lib:format("Failed to move ~ts to ~ts~n",
  297. [filename:join(SrcPath, FileName),
  298. filename:join(DestPath, FileName)]))};
  299. true ->
  300. ok
  301. end.
  302. robocopy_dir(Source, Dest) ->
  303. Cmd = ?FMT("robocopy /move /e \"~ts\" \"~ts\"",
  304. [rebar_utils:escape_double_quotes(Source),
  305. rebar_utils:escape_double_quotes(Dest)]),
  306. Res = rebar_utils:sh(Cmd,
  307. [{use_stdout, false}, return_on_error]),
  308. case win32_ok(Res) of
  309. true -> ok;
  310. false ->
  311. {error, lists:flatten(
  312. io_lib:format("Failed to move ~ts to ~ts~n",
  313. [Source, Dest]))}
  314. end.
  315. win32_ok({ok, _}) -> true;
  316. win32_ok({error, {Rc, _}}) when Rc<9; Rc=:=16 -> true;
  317. win32_ok(_) -> false.
  318. delete_each([]) ->
  319. ok;
  320. delete_each([File | Rest]) ->
  321. case file:delete(File) of
  322. ok ->
  323. delete_each(Rest);
  324. {error, enoent} ->
  325. delete_each(Rest);
  326. {error, Reason} ->
  327. ?ERROR("Failed to delete file ~ts: ~p\n", [File, Reason]),
  328. ?FAIL
  329. end.
  330. %% @doc backwards compat layer to pre-utf8 support
  331. write_file_if_contents_differ(Filename, Bytes) ->
  332. write_file_if_contents_differ(Filename, Bytes, raw).
  333. %% @doc let the user pick the encoding required; there are no good
  334. %% heuristics for data encoding
  335. write_file_if_contents_differ(Filename, Bytes, raw) ->
  336. write_file_if_contents_differ_(Filename, iolist_to_binary(Bytes));
  337. write_file_if_contents_differ(Filename, Bytes, utf8) ->
  338. write_file_if_contents_differ_(Filename, unicode:characters_to_binary(Bytes, utf8)).
  339. %% @private compare raw strings and check contents
  340. write_file_if_contents_differ_(Filename, ToWrite) ->
  341. case file:read_file(Filename) of
  342. {ok, ToWrite} ->
  343. ok;
  344. {ok, _} ->
  345. file:write_file(Filename, ToWrite, [raw]);
  346. {error, _} ->
  347. file:write_file(Filename, ToWrite, [raw])
  348. end.
  349. %% returns an os appropriate tmpdir given a path
  350. -spec system_tmpdir() -> file:filename().
  351. system_tmpdir() -> system_tmpdir([]).
  352. -spec system_tmpdir(PathComponents) -> file:filename() when
  353. PathComponents :: [file:name()].
  354. system_tmpdir(PathComponents) ->
  355. Tmp = case erlang:system_info(system_architecture) of
  356. "win32" ->
  357. "./tmp";
  358. _SysArch ->
  359. "/tmp"
  360. end,
  361. filename:join([Tmp|PathComponents]).
  362. %% recursively removes a directory and then recreates the same
  363. %% directory but empty
  364. -spec reset_dir(Path) -> ok | {error, Reason} when
  365. Path :: file:name(),
  366. Reason :: file:posix().
  367. reset_dir(Path) ->
  368. %% delete the directory if it exists
  369. _ = ec_file:remove(Path, [recursive]),
  370. %% recreate the directory
  371. ensure_dir(Path).
  372. %% Linux touch but using erlang functions to work in bot *nix os and
  373. %% windows
  374. -spec touch(Path) -> ok | {error, Reason} when
  375. Path :: file:name(),
  376. Reason :: file:posix().
  377. touch(Path) ->
  378. {ok, A} = file:read_file_info(Path),
  379. ok = file:write_file_info(Path, A#file_info{mtime = calendar:local_time(),
  380. atime = calendar:local_time()}).
  381. %% for a given path return the path relative to a base directory
  382. -spec path_from_ancestor(string(), string()) -> {ok, string()} | {error, badparent}.
  383. path_from_ancestor(Target, To) ->
  384. path_from_ancestor_(filename:split(canonical_path(Target)),
  385. filename:split(canonical_path(To))).
  386. path_from_ancestor_([Part|Target], [Part|To]) -> path_from_ancestor_(Target, To);
  387. path_from_ancestor_([], []) -> {ok, ""};
  388. path_from_ancestor_(Target, []) -> {ok, filename:join(Target)};
  389. path_from_ancestor_(_, _) -> {error, badparent}.
  390. %% reduce a filepath by removing all incidences of `.' and `..'
  391. -spec canonical_path(string()) -> string().
  392. canonical_path(Dir) ->
  393. Canon = canonical_path([], filename:split(filename:absname(Dir))),
  394. filename:nativename(Canon).
  395. canonical_path([], []) -> filename:absname("/");
  396. canonical_path(Acc, []) -> filename:join(lists:reverse(Acc));
  397. canonical_path(Acc, ["."|Rest]) -> canonical_path(Acc, Rest);
  398. canonical_path([_|Acc], [".."|Rest]) -> canonical_path(Acc, Rest);
  399. canonical_path([], [".."|Rest]) -> canonical_path([], Rest);
  400. canonical_path(Acc, [Component|Rest]) -> canonical_path([Component|Acc], Rest).
  401. %% @doc returns canonical target of path if path is a link, otherwise returns path
  402. -spec resolve_link(string()) -> string().
  403. resolve_link(Path) ->
  404. case file:read_link(Path) of
  405. {ok, Target} ->
  406. canonical_path(filename:absname(Target, filename:dirname(Path)));
  407. {error, _} -> Path
  408. end.
  409. %% @doc splits a path into dirname and basename
  410. -spec split_dirname(string()) -> {string(), string()}.
  411. split_dirname(Path) ->
  412. {filename:dirname(Path), filename:basename(Path)}.
  413. -spec ensure_dir(filelib:dirname_all()) -> ok | {error, file:posix()}.
  414. ensure_dir(Path) ->
  415. filelib:ensure_dir(filename:join(Path, "fake_file")).
  416. %% ===================================================================
  417. %% Internal functions
  418. %% ===================================================================
  419. delete_each_dir_win32([]) -> ok;
  420. delete_each_dir_win32([Dir | Rest]) ->
  421. {ok, []} = rebar_utils:sh(?FMT("rd /q /s \"~ts\"",
  422. [rebar_utils:escape_double_quotes(filename:nativename(Dir))]),
  423. [{use_stdout, false}, return_on_error]),
  424. delete_each_dir_win32(Rest).
  425. xcopy_win32(Source,Dest)->
  426. %% "xcopy \"~ts\" \"~ts\" /q /y /e 2> nul", Changed to robocopy to
  427. %% handle long names. May have issues with older windows.
  428. Cmd = case filelib:is_dir(Source) of
  429. true ->
  430. %% For robocopy, copying /a/b/c/ to /d/e/f/ recursively does not
  431. %% create /d/e/f/c/*, but rather copies all files to /d/e/f/*.
  432. %% The usage we make here expects the former, not the later, so we
  433. %% must manually add the last fragment of a directory to the `Dest`
  434. %% in order to properly replicate POSIX platforms
  435. NewDest = filename:join([Dest, filename:basename(Source)]),
  436. ?FMT("robocopy \"~ts\" \"~ts\" /e 1> nul",
  437. [rebar_utils:escape_double_quotes(filename:nativename(Source)),
  438. rebar_utils:escape_double_quotes(filename:nativename(NewDest))]);
  439. false ->
  440. ?FMT("robocopy \"~ts\" \"~ts\" \"~ts\" /e 1> nul",
  441. [rebar_utils:escape_double_quotes(filename:nativename(filename:dirname(Source))),
  442. rebar_utils:escape_double_quotes(filename:nativename(Dest)),
  443. rebar_utils:escape_double_quotes(filename:basename(Source))])
  444. end,
  445. Res = rebar_utils:sh(Cmd,
  446. [{use_stdout, false}, return_on_error]),
  447. case win32_ok(Res) of
  448. true -> ok;
  449. false ->
  450. {error, lists:flatten(
  451. io_lib:format("Failed to copy ~ts to ~ts~n",
  452. [Source, Dest]))}
  453. end.
  454. cp_r_win32({true, SourceDir}, {true, DestDir}) ->
  455. %% from directory to directory
  456. ok = case file:make_dir(DestDir) of
  457. {error, eexist} -> ok;
  458. Other -> Other
  459. end,
  460. ok = xcopy_win32(SourceDir, DestDir);
  461. cp_r_win32({false, Source} = S,{true, DestDir}) ->
  462. %% from file to directory
  463. cp_r_win32(S, {false, filename:join(DestDir, filename:basename(Source))});
  464. cp_r_win32({false, Source},{false, Dest}) ->
  465. %% from file to file
  466. {ok,_} = file:copy(Source, Dest),
  467. ok;
  468. cp_r_win32({true, SourceDir}, {false, DestDir}) ->
  469. case filelib:is_regular(DestDir) of
  470. true ->
  471. %% From directory to file? This shouldn't happen
  472. {error, lists:flatten(
  473. io_lib:format("Cannot copy dir (~p) to file (~p)\n",
  474. [SourceDir, DestDir]))};
  475. false ->
  476. %% Specifying a target directory that doesn't currently exist.
  477. %% So let's attempt to create this directory
  478. case ensure_dir(DestDir) of
  479. ok ->
  480. ok = xcopy_win32(SourceDir, DestDir);
  481. {error, Reason} ->
  482. {error, lists:flatten(
  483. io_lib:format("Unable to create dir ~p: ~p\n",
  484. [DestDir, Reason]))}
  485. end
  486. end;
  487. cp_r_win32(Source,Dest) ->
  488. Dst = {filelib:is_dir(Dest), Dest},
  489. lists:foreach(fun(Src) ->
  490. ok = cp_r_win32({filelib:is_dir(Src), Src}, Dst)
  491. end, filelib:wildcard(Source)),
  492. ok.