Skip to content

Commit

Permalink
Fix renaming a dir with sub-directories
Browse files Browse the repository at this point in the history
  • Loading branch information
nono committed Apr 11, 2020
1 parent ceb6a5e commit a38f79b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
14 changes: 13 additions & 1 deletion memmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func (m *MemMapFs) RemoveAll(path string) error {
defer m.mu.RUnlock()

for p := range m.getData() {
if strings.HasPrefix(p, path) {
if strings.HasPrefix(p, path+FilePathSeparator) {
m.mu.RUnlock()
m.mu.Lock()
delete(m.getData(), p)
Expand Down Expand Up @@ -305,6 +305,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
44 changes: 44 additions & 0 deletions memmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -449,3 +449,47 @@ func TestMemFsUnexpectedEOF(t *testing.T) {
t.Fatal("Expected ErrUnexpectedEOF")
}
}

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

fs := NewMemMapFs()

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

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

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

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

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

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

0 comments on commit a38f79b

Please sign in to comment.