Initial commit

This commit is contained in:
Miroslav Misek 2025-03-27 08:58:59 +01:00
commit f146f95efc
5 changed files with 94 additions and 0 deletions

8
.idea/mergefs.iml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/mergefs.iml" filepath="$PROJECT_DIR$/.idea/mergefs.iml" />
</modules>
</component>
</project>

9
.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectViewState">
<option name="autoscrollFromSource" value="true" />
<option name="autoscrollToSource" value="true" />
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
</project>

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module netgarden.dev/netgarden/mergefs
go 1.24.1

66
mergefs.go Normal file
View File

@ -0,0 +1,66 @@
package mergefs
import (
"errors"
"io/fs"
"os"
)
// Merge merges the given filesystems together,
func Merge(filesystems ...fs.FS) fs.FS {
return MergedFS{filesystems: filesystems}
}
// MergedFS combines filesystems. Each filesystem can serve different paths.
// The first FS takes precedence
type MergedFS struct {
filesystems []fs.FS
}
// Open opens the named file.
func (mfs MergedFS) Open(name string) (fs.File, error) {
for _, fs := range mfs.filesystems {
file, err := fs.Open(name)
if err == nil { // TODO should we return early when it's not an os.ErrNotExist? Should we offer options to decide this behaviour?
return file, nil
}
}
return nil, os.ErrNotExist
}
// ReadDir reads from the directory, and produces a DirEntry array of different
// directories.
//
// It iterates through all different filesystems that exist in the mfs MergeFS
// filesystem slice and it identifies overlapping directories that exist in different
// filesystems
func (mfs MergedFS) ReadDir(name string) ([]fs.DirEntry, error) {
dirsMap := make(map[string]fs.DirEntry)
notExistCount := 0
for _, filesystem := range mfs.filesystems {
dir, err := fs.ReadDir(filesystem, name)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
notExistCount++
continue
}
return nil, err
}
for _, v := range dir {
if _, ok := dirsMap[v.Name()]; !ok {
dirsMap[v.Name()] = v
}
}
continue
}
if len(mfs.filesystems) == notExistCount {
return nil, fs.ErrNotExist
}
dirs := make([]fs.DirEntry, 0, len(dirsMap))
for _, value := range dirsMap {
dirs = append(dirs, value)
}
return dirs, nil
}