Skip to content

Commit 8a5e7c8

Browse files
authored
Add 'rename/2' to z_filelib (#106)
1 parent 044a295 commit 8a5e7c8

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/z_filelib.erl

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
%% @author Marc Worrell <[email protected]>
2-
%% @copyright 2017-2021 Marc Worrell
3-
%%
2+
%% @copyright 2017-2025 Marc Worrell
43
%% @doc Extra file functions.
4+
%% @end
55

6-
%% Copyright 2017-2021 Marc Worrell
6+
%% Copyright 2017-2025 Marc Worrell
77
%%
88
%% Licensed under the Apache License, Version 2.0 (the "License");
99
%% you may not use this file except in compliance with the License.
@@ -20,11 +20,33 @@
2020
-module(z_filelib).
2121

2222
-export([
23+
rename/2,
2324
ensure_dir/1,
2425
os_filename/1,
2526
os_escape/1
2627
]).
2728

29+
30+
%% @doc Rename a file. Copy the file on a cross-fs error.
31+
-spec rename(From, To) -> ok | {error, term()} when
32+
From :: file:filename_all(),
33+
To :: file:filename_all().
34+
rename(From, To) ->
35+
case file:rename(From, To) of
36+
ok ->
37+
ok;
38+
{error, exdev} ->
39+
% cross-fs rename is not supported by erlang, so copy and delete the file
40+
case file:copy(From, To) of
41+
{ok, _BytesCopied} ->
42+
ok = file:delete(From);
43+
{error, _} = Error ->
44+
Error
45+
end;
46+
{error, _} = Error ->
47+
Error
48+
end.
49+
2850
%% @doc Ensure the directory of a file is present. This will still work
2951
%% if a soft-link in the path refers to a missing directory.
3052
-spec ensure_dir(file:filename_all()) -> ok | {error, term()}.

0 commit comments

Comments
 (0)