您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

602 行
24 KiB

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