fileutil.Replace - remove destination only when a directory.

In cases where a rename fails the fileutil.Replace would delete the
source files/folder.

There is no easy way to make directory renaming atomic, but for files
os.Rename is atomic and replaced the destination file so there is no
need to remove the destination file explicitly.

Signed-off-by: Krasi Georgiev <8903888+krasi-georgiev@users.noreply.github.com>
This commit is contained in:
Krasi Georgiev 2019-06-19 12:10:51 +03:00
parent c2c921af75
commit 5d27fc48a8

View file

@ -128,9 +128,20 @@ func Rename(from, to string) error {
// Replace moves a file or directory to a new location and deletes any previous data.
// It is not atomic.
func Replace(from, to string) error {
if err := os.RemoveAll(to); err != nil {
return err
// Remove destionation only if it is a dir.
// Otherwise os.Rename replaces the destination file and is atomic.
{
f, err := os.Stat(to)
if err != nil {
return err
}
if f.IsDir() {
if err := os.RemoveAll(to); err != nil {
return err
}
}
}
if err := os.Rename(from, to); err != nil {
return err
}