Skip to content

Commit 3b1116b

Browse files
authored
memmap: Fix renaming a dir with sub-directories (#239)
Fixes ##141
1 parent a800a9d commit 3b1116b

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

memmap.go

+12
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,18 @@ func (m *MemMapFs) Rename(oldname, newname string) error {
319319
} else {
320320
return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
321321
}
322+
323+
for p, fileData := range m.getData() {
324+
if strings.HasPrefix(p, oldname+FilePathSeparator) {
325+
m.mu.RUnlock()
326+
m.mu.Lock()
327+
delete(m.getData(), p)
328+
p := strings.Replace(p, oldname, newname, 1)
329+
m.getData()[p] = fileData
330+
m.mu.Unlock()
331+
m.mu.RLock()
332+
}
333+
}
322334
return nil
323335
}
324336

memmap_test.go

+57
Original file line numberDiff line numberDiff line change
@@ -776,3 +776,60 @@ func TestMemMapFsConfurrentMkdir(t *testing.T) {
776776
t.Errorf("found %d files, but expect %d", len(foundFiles), n)
777777
}
778778
}
779+
780+
func TestMemFsRenameDir(t *testing.T) {
781+
const srcPath = "/src"
782+
const dstPath = "/dst"
783+
const subDir = "dir"
784+
const subFile = "file.txt"
785+
786+
fs := NewMemMapFs()
787+
788+
err := fs.MkdirAll(srcPath+FilePathSeparator+subDir, 0777)
789+
if err != nil {
790+
t.Fatalf("MkDirAll failed: %s", err)
791+
}
792+
793+
f, err := fs.Create(srcPath + FilePathSeparator + subFile)
794+
if err != nil {
795+
t.Fatalf("Create failed: %s", err)
796+
}
797+
if err = f.Close(); err != nil {
798+
t.Fatalf("Close failed: %s", err)
799+
}
800+
801+
err = fs.Rename(srcPath, dstPath)
802+
if err != nil {
803+
t.Fatalf("Rename failed: %s", err)
804+
}
805+
806+
_, err = fs.Stat(srcPath + FilePathSeparator + subDir)
807+
if err == nil {
808+
t.Fatalf("SubDir still exists in the source dir")
809+
}
810+
811+
_, err = fs.Stat(srcPath + FilePathSeparator + subFile)
812+
if err == nil {
813+
t.Fatalf("SubFile still exists in the source dir")
814+
}
815+
816+
_, err = fs.Stat(dstPath + FilePathSeparator + subDir)
817+
if err != nil {
818+
t.Fatalf("SubDir stat in the destination dir: %s", err)
819+
}
820+
821+
_, err = fs.Stat(dstPath + FilePathSeparator + subFile)
822+
if err != nil {
823+
t.Fatalf("SubFile stat in the destination dir: %s", err)
824+
}
825+
826+
err = fs.Mkdir(srcPath, 0777)
827+
if err != nil {
828+
t.Fatalf("Cannot recreate the source dir: %s", err)
829+
}
830+
831+
err = fs.Mkdir(srcPath+FilePathSeparator+subDir, 0777)
832+
if err != nil {
833+
t.Errorf("Cannot recreate the subdir in the source dir: %s", err)
834+
}
835+
}

0 commit comments

Comments
 (0)