Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

518 rindas
20 KiB

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