Skip to content

Commit

Permalink
memmap: Fix renaming a dir with sub-directories (#239)
Browse files Browse the repository at this point in the history
Fixes ##141
  • Loading branch information
nono committed Feb 23, 2023
1 parent a800a9d commit 3b1116b
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
12 changes: 12 additions & 0 deletions memmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,18 @@ func (m *MemMapFs) Rename(oldname, newname string) error {
} else {
return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
}

for p, fileData := range m.getData() {
if strings.HasPrefix(p, oldname+FilePathSeparator) {
m.mu.RUnlock()
m.mu.Lock()
delete(m.getData(), p)
p := strings.Replace(p, oldname, newname, 1)
m.getData()[p] = fileData
m.mu.Unlock()
m.mu.RLock()
}
}
return nil
}

Expand Down
57 changes: 57 additions & 0 deletions memmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -776,3 +776,60 @@ func TestMemMapFsConfurrentMkdir(t *testing.T) {
t.Errorf("found %d files, but expect %d", len(foundFiles), n)
}
}

func TestMemFsRenameDir(t *testing.T) {
const srcPath = "/src"
const dstPath = "/dst"
const subDir = "dir"
const subFile = "file.txt"

fs := NewMemMapFs()

err := fs.MkdirAll(srcPath+FilePathSeparator+subDir, 0777)
if err != nil {
t.Fatalf("MkDirAll failed: %s", err)
}

f, err := fs.Create(srcPath + FilePathSeparator + subFile)
if err != nil {
t.Fatalf("Create failed: %s", err)
}
if err = f.Close(); err != nil {
t.Fatalf("Close failed: %s", err)
}

err = fs.Rename(srcPath, dstPath)
if err != nil {
t.Fatalf("Rename failed: %s", err)
}

_, err = fs.Stat(srcPath + FilePathSeparator + subDir)
if err == nil {
t.Fatalf("SubDir still exists in the source dir")
}

_, err = fs.Stat(srcPath + FilePathSeparator + subFile)
if err == nil {
t.Fatalf("SubFile still exists in the source dir")
}

_, err = fs.Stat(dstPath + FilePathSeparator + subDir)
if err != nil {
t.Fatalf("SubDir stat in the destination dir: %s", err)
}

_, err = fs.Stat(dstPath + FilePathSeparator + subFile)
if err != nil {
t.Fatalf("SubFile stat in the destination dir: %s", err)
}

err = fs.Mkdir(srcPath, 0777)
if err != nil {
t.Fatalf("Cannot recreate the source dir: %s", err)
}

err = fs.Mkdir(srcPath+FilePathSeparator+subDir, 0777)
if err != nil {
t.Errorf("Cannot recreate the subdir in the source dir: %s", err)
}
}

0 comments on commit 3b1116b

Please sign in to comment.