Skip to content

Commit 892c8da

Browse files
committed
Improved error handling in moveAll function
We are now explicit that we os.Rename only if the target directory does not exist (os.IsNotExist(err)) and we don't do that if it's any other type of an error. In such case, we return from the function doing nothing. We also no longer ignore errors from ioutil.ReadDir. If the error happens, we return the function doing nothing.
1 parent c2c64e9 commit 892c8da

1 file changed

Lines changed: 30 additions & 15 deletions

File tree

pkg/persistence/disk_persistence.go

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -210,25 +210,40 @@ func readAll(directoryPath string) (<-chan DataDescriptor, <-chan error) {
210210
}
211211

212212
func moveAll(directoryFromPath, directoryToPath string) error {
213-
if _, err := os.Stat(directoryToPath); !os.IsNotExist(err) {
214-
files, _ := ioutil.ReadDir(directoryFromPath)
215-
for _, file := range files {
216-
from := fmt.Sprintf("%s/%s", directoryFromPath, file.Name())
217-
to := fmt.Sprintf("%s/%s", directoryToPath, file.Name())
218-
err := os.Rename(from, to)
219-
if err != nil {
220-
return err
221-
}
222-
}
223-
err = os.RemoveAll(directoryFromPath)
224-
if err != nil {
225-
return fmt.Errorf("error occurred while removing archived dir: [%v]", err)
226-
}
227-
} else {
213+
_, err := os.Stat(directoryToPath)
214+
215+
// target directory does not exist, we can move everything
216+
if os.IsNotExist(err) {
228217
err := os.Rename(directoryFromPath, directoryToPath)
229218
if err != nil {
230219
return fmt.Errorf("error occurred while moving a dir: [%v]", err)
231220
}
221+
222+
return nil
223+
}
224+
225+
// unexpected error occurred while checking target directory existence,
226+
// returning
227+
if err != nil {
228+
return fmt.Errorf("could not stat target directory: [%v]", err)
229+
}
230+
231+
// target directory does exit, we need to append files
232+
files, err := ioutil.ReadDir(directoryFromPath)
233+
if err != nil {
234+
return fmt.Errorf("could not read directory [%v]: [%v]", directoryFromPath, err)
235+
}
236+
for _, file := range files {
237+
from := fmt.Sprintf("%s/%s", directoryFromPath, file.Name())
238+
to := fmt.Sprintf("%s/%s", directoryToPath, file.Name())
239+
err := os.Rename(from, to)
240+
if err != nil {
241+
return err
242+
}
243+
}
244+
err = os.RemoveAll(directoryFromPath)
245+
if err != nil {
246+
return fmt.Errorf("error occurred while removing archived dir: [%v]", err)
232247
}
233248

234249
return nil

0 commit comments

Comments
 (0)