afero/memmap.go

466 lines
9.9 KiB
Go
Raw Normal View History

2014-10-28 17:29:28 +03:00
// Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package afero
import (
2014-12-12 21:32:57 +03:00
"fmt"
2023-03-06 12:18:15 +03:00
"io"
"log"
2014-10-28 17:29:28 +03:00
"os"
"path/filepath"
"sort"
2014-10-28 17:29:28 +03:00
"strings"
"sync"
2014-11-01 06:36:45 +03:00
"time"
"github.com/spf13/afero/mem"
2014-10-28 17:29:28 +03:00
)
const chmodBits = os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky // Only a subset of bits are allowed to be changed. Documented under os.Chmod()
2014-10-28 17:29:28 +03:00
type MemMapFs struct {
2015-12-18 23:26:04 +03:00
mu sync.RWMutex
data map[string]*mem.FileData
init sync.Once
2014-10-28 17:29:28 +03:00
}
func NewMemMapFs() Fs {
return &MemMapFs{}
}
func (m *MemMapFs) getData() map[string]*mem.FileData {
m.init.Do(func() {
m.data = make(map[string]*mem.FileData)
2015-12-03 00:27:14 +03:00
// Root should always exist, right?
// TODO: what about windows?
root := mem.CreateDir(FilePathSeparator)
2023-02-23 12:14:33 +03:00
mem.SetMode(root, os.ModeDir|0o755)
m.data[FilePathSeparator] = root
})
2014-10-28 17:29:28 +03:00
return m.data
}
2017-01-10 01:53:20 +03:00
func (*MemMapFs) Name() string { return "MemMapFS" }
2014-10-28 17:29:28 +03:00
func (m *MemMapFs) Create(name string) (File, error) {
name = normalizePath(name)
2015-12-18 23:26:04 +03:00
m.mu.Lock()
2015-12-10 21:00:25 +03:00
file := mem.CreateFile(name)
m.getData()[name] = file
m.registerWithParent(file, 0)
2015-12-18 23:26:04 +03:00
m.mu.Unlock()
return mem.NewFileHandle(file), nil
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) unRegisterWithParent(fileName string) error {
f, err := m.lockfreeOpen(fileName)
if err != nil {
return err
2014-10-28 17:29:28 +03:00
}
parent := m.findParent(f)
if parent == nil {
log.Panic("parent of ", f.Name(), " is nil")
}
parent.Lock()
mem.RemoveFromMemDir(parent, f)
parent.Unlock()
return nil
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData {
pdir, _ := filepath.Split(f.Name())
pdir = filepath.Clean(pdir)
pfile, err := m.lockfreeOpen(pdir)
if err != nil {
return nil
2014-10-28 17:29:28 +03:00
}
return pfile
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) findDescendants(name string) []*mem.FileData {
fData := m.getData()
descendants := make([]*mem.FileData, 0, len(fData))
for p, dFile := range fData {
if strings.HasPrefix(p, name+FilePathSeparator) {
descendants = append(descendants, dFile)
}
}
sort.Slice(descendants, func(i, j int) bool {
cur := len(strings.Split(descendants[i].Name(), FilePathSeparator))
next := len(strings.Split(descendants[j].Name(), FilePathSeparator))
return cur < next
})
return descendants
}
func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) {
2014-10-28 17:29:28 +03:00
if f == nil {
return
2014-10-28 17:29:28 +03:00
}
parent := m.findParent(f)
if parent == nil {
pdir := filepath.Dir(filepath.Clean(f.Name()))
err := m.lockfreeMkdir(pdir, perm)
if err != nil {
2023-02-23 12:14:33 +03:00
// log.Println("Mkdir error:", err)
return
}
parent, err = m.lockfreeOpen(pdir)
if err != nil {
2023-02-23 12:14:33 +03:00
// log.Println("Open after Mkdir error:", err)
return
}
2014-10-28 17:29:28 +03:00
}
parent.Lock()
mem.InitializeDir(parent)
mem.AddToMemDir(parent, f)
parent.Unlock()
}
func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error {
name = normalizePath(name)
x, ok := m.getData()[name]
if ok {
// Only return ErrFileExists if it's a file, not a directory.
2017-01-10 01:53:20 +03:00
i := mem.FileInfo{FileData: x}
if !i.IsDir() {
return ErrFileExists
}
} else {
2015-12-10 21:00:25 +03:00
item := mem.CreateDir(name)
mem.SetMode(item, os.ModeDir|perm)
m.getData()[name] = item
m.registerWithParent(item, perm)
}
return nil
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error {
perm &= chmodBits
name = normalizePath(name)
2015-12-18 23:26:04 +03:00
m.mu.RLock()
_, ok := m.getData()[name]
2015-12-18 23:26:04 +03:00
m.mu.RUnlock()
2014-10-28 17:29:28 +03:00
if ok {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists}
2014-10-28 17:29:28 +03:00
}
m.mu.Lock()
// Dobule check that it doesn't exist.
if _, ok := m.getData()[name]; ok {
m.mu.Unlock()
return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists}
}
item := mem.CreateDir(name)
mem.SetMode(item, os.ModeDir|perm)
m.getData()[name] = item
m.registerWithParent(item, perm)
m.mu.Unlock()
return m.setFileMode(name, perm|os.ModeDir)
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error {
err := m.Mkdir(path, perm)
if err != nil {
if err.(*os.PathError).Err == ErrFileExists {
return nil
}
return err
}
return nil
2014-10-28 17:29:28 +03:00
}
// Handle some relative paths
func normalizePath(path string) string {
path = filepath.Clean(path)
switch path {
case ".":
2015-12-09 23:37:04 +03:00
return FilePathSeparator
case "..":
2015-12-09 23:37:04 +03:00
return FilePathSeparator
default:
return path
}
}
2014-10-28 17:29:28 +03:00
func (m *MemMapFs) Open(name string) (File, error) {
f, err := m.open(name)
if f != nil {
return mem.NewReadOnlyFileHandle(f), err
}
return nil, err
}
func (m *MemMapFs) openWrite(name string) (File, error) {
f, err := m.open(name)
if f != nil {
return mem.NewFileHandle(f), err
}
return nil, err
}
func (m *MemMapFs) open(name string) (*mem.FileData, error) {
name = normalizePath(name)
2015-12-18 23:26:04 +03:00
m.mu.RLock()
2014-10-28 17:29:28 +03:00
f, ok := m.getData()[name]
2015-12-18 23:26:04 +03:00
m.mu.RUnlock()
if !ok {
2017-01-10 01:53:20 +03:00
return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound}
2014-10-28 17:29:28 +03:00
}
return f, nil
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) {
name = normalizePath(name)
f, ok := m.getData()[name]
if ok {
return f, nil
} else {
return nil, ErrFileNotFound
}
}
2014-10-28 17:29:28 +03:00
func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
perm &= chmodBits
chmod := false
file, err := m.openWrite(name)
if err == nil && (flag&(os.O_CREATE|os.O_EXCL)) == (os.O_CREATE|os.O_EXCL) {
return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileExists}
}
if os.IsNotExist(err) && (flag&os.O_CREATE > 0) {
file, err = m.Create(name)
chmod = true
}
if err != nil {
return nil, err
}
if flag == os.O_RDONLY {
file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data())
}
if flag&os.O_APPEND > 0 {
2023-03-06 12:18:15 +03:00
_, err = file.Seek(0, io.SeekEnd)
if err != nil {
file.Close()
return nil, err
}
}
if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 {
err = file.Truncate(0)
if err != nil {
file.Close()
return nil, err
}
}
if chmod {
return file, m.setFileMode(name, perm)
}
return file, nil
2014-10-28 17:29:28 +03:00
}
func (m *MemMapFs) Remove(name string) error {
name = normalizePath(name)
2015-12-18 23:26:04 +03:00
m.mu.Lock()
defer m.mu.Unlock()
2014-10-28 17:29:28 +03:00
if _, ok := m.getData()[name]; ok {
err := m.unRegisterWithParent(name)
if err != nil {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "remove", Path: name, Err: err}
}
2014-10-28 17:29:28 +03:00
delete(m.getData(), name)
} else {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist}
2014-10-28 17:29:28 +03:00
}
return nil
}
func (m *MemMapFs) RemoveAll(path string) error {
path = normalizePath(path)
2015-12-18 23:26:04 +03:00
m.mu.Lock()
m.unRegisterWithParent(path)
2015-12-18 23:26:04 +03:00
m.mu.Unlock()
2015-12-18 23:26:04 +03:00
m.mu.RLock()
defer m.mu.RUnlock()
2020-04-11 00:50:34 +03:00
for p := range m.getData() {
if p == path || strings.HasPrefix(p, path+FilePathSeparator) {
2015-12-18 23:26:04 +03:00
m.mu.RUnlock()
m.mu.Lock()
2014-10-28 17:29:28 +03:00
delete(m.getData(), p)
2015-12-18 23:26:04 +03:00
m.mu.Unlock()
m.mu.RLock()
2014-10-28 17:29:28 +03:00
}
}
return nil
}
func (m *MemMapFs) Rename(oldname, newname string) error {
oldname = normalizePath(oldname)
newname = normalizePath(newname)
if oldname == newname {
return nil
}
2015-12-18 23:26:04 +03:00
m.mu.RLock()
defer m.mu.RUnlock()
2014-10-28 17:29:28 +03:00
if _, ok := m.getData()[oldname]; ok {
m.mu.RUnlock()
m.mu.Lock()
err := m.unRegisterWithParent(oldname)
if err != nil {
return err
}
fileData := m.getData()[oldname]
mem.ChangeFileName(fileData, newname)
m.getData()[newname] = fileData
err = m.renameDescendants(oldname, newname)
if err != nil {
return err
}
delete(m.getData(), oldname)
m.registerWithParent(fileData, 0)
m.mu.Unlock()
m.mu.RLock()
2014-10-28 17:29:28 +03:00
} else {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
2014-10-28 17:29:28 +03:00
}
return nil
}
func (m *MemMapFs) renameDescendants(oldname, newname string) error {
descendants := m.findDescendants(oldname)
removes := make([]string, 0, len(descendants))
for _, desc := range descendants {
descNewName := strings.Replace(desc.Name(), oldname, newname, 1)
err := m.unRegisterWithParent(desc.Name())
if err != nil {
return err
}
removes = append(removes, desc.Name())
mem.ChangeFileName(desc, descNewName)
m.getData()[descNewName] = desc
m.registerWithParent(desc, 0)
}
for _, r := range removes {
delete(m.getData(), r)
}
2014-10-28 17:29:28 +03:00
return nil
}
2020-09-07 08:05:27 +03:00
func (m *MemMapFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
fileInfo, err := m.Stat(name)
return fileInfo, false, err
}
2014-10-28 17:29:28 +03:00
func (m *MemMapFs) Stat(name string) (os.FileInfo, error) {
f, err := m.Open(name)
if err != nil {
return nil, err
}
fi := mem.GetFileInfo(f.(*mem.File).Data())
2015-12-10 21:00:25 +03:00
return fi, nil
2014-10-28 17:29:28 +03:00
}
2014-11-01 06:36:45 +03:00
func (m *MemMapFs) Chmod(name string, mode os.FileMode) error {
mode &= chmodBits
m.mu.RLock()
2014-11-01 06:36:45 +03:00
f, ok := m.getData()[name]
m.mu.RUnlock()
2014-11-01 06:36:45 +03:00
if !ok {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
2014-11-01 06:36:45 +03:00
}
prevOtherBits := mem.GetFileInfo(f).Mode() & ^chmodBits
2014-11-01 06:36:45 +03:00
mode = prevOtherBits | mode
return m.setFileMode(name, mode)
2014-11-01 06:36:45 +03:00
}
func (m *MemMapFs) setFileMode(name string, mode os.FileMode) error {
name = normalizePath(name)
m.mu.RLock()
2014-11-01 06:36:45 +03:00
f, ok := m.getData()[name]
m.mu.RUnlock()
2014-11-01 06:36:45 +03:00
if !ok {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
2014-11-01 06:36:45 +03:00
}
m.mu.Lock()
mem.SetMode(f, mode)
m.mu.Unlock()
2014-11-01 06:36:45 +03:00
return nil
}
2014-12-12 21:32:57 +03:00
2020-01-22 17:25:31 +03:00
func (m *MemMapFs) Chown(name string, uid, gid int) error {
name = normalizePath(name)
m.mu.RLock()
f, ok := m.getData()[name]
m.mu.RUnlock()
if !ok {
return &os.PathError{Op: "chown", Path: name, Err: ErrFileNotFound}
}
mem.SetUID(f, uid)
mem.SetGID(f, gid)
return nil
}
2020-12-07 16:19:45 +03:00
2014-11-01 06:36:45 +03:00
func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
name = normalizePath(name)
m.mu.RLock()
2014-11-01 06:36:45 +03:00
f, ok := m.getData()[name]
m.mu.RUnlock()
2014-11-01 06:36:45 +03:00
if !ok {
2017-01-10 01:53:20 +03:00
return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound}
2014-11-01 06:36:45 +03:00
}
m.mu.Lock()
mem.SetModTime(f, mtime)
m.mu.Unlock()
2014-11-01 06:36:45 +03:00
return nil
}
2014-12-12 21:32:57 +03:00
func (m *MemMapFs) List() {
for _, x := range m.data {
2017-01-10 01:53:20 +03:00
y := mem.FileInfo{FileData: x}
fmt.Println(x.Name(), y.Size())
2014-12-12 21:32:57 +03:00
}
}