Skip to content
This repository was archived by the owner on Aug 13, 2019. It is now read-only.

Commit b5f9f9f

Browse files
authored
Merge pull request #636 from krasi-georgiev/rename-bug
fileutil.Replace - remove destination only when a directory.
2 parents d501ae4 + 251c3a4 commit b5f9f9f

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

fileutil/fileutil.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,19 @@ func Rename(from, to string) error {
128128
// Replace moves a file or directory to a new location and deletes any previous data.
129129
// It is not atomic.
130130
func Replace(from, to string) error {
131-
if err := os.RemoveAll(to); err != nil {
132-
return err
131+
// Remove destination only if it is a dir otherwise leave it to os.Rename
132+
// as it replaces the destination file and is atomic.
133+
{
134+
f, err := os.Stat(to)
135+
if !os.IsNotExist(err) {
136+
if err == nil && f.IsDir() {
137+
if err := os.RemoveAll(to); err != nil {
138+
return err
139+
}
140+
}
141+
}
133142
}
143+
134144
if err := os.Rename(from, to); err != nil {
135145
return err
136146
}

0 commit comments

Comments
 (0)