-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsfmapper.go
82 lines (68 loc) · 1.79 KB
/
sfmapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package sfmapper
import (
"fmt"
"reflect"
"bazil.org/fuse"
"bazil.org/fuse/fs"
"github.com/IslamWalid/sfmapper/internal/fsnode"
"github.com/fatih/structs"
)
// FS represents file system type.
type FS struct {
// Reference to the struct that the user need to represent in the file system.
UserStructRef any
}
// newFS Creates new file system object
func newFS(userStruct any) *FS {
return &FS{
UserStructRef: userStruct,
}
}
// Mount mounts the file system to the given mount point and starts the file system server.
func Mount(mountPointPath string, userStruct any) error {
conn, err := fuse.Mount(mountPointPath)
if err != nil {
return err
}
err = fs.Serve(conn, newFS(userStruct))
if err != nil {
return err
}
err = conn.Close()
if err != nil {
return err
}
return nil
}
func UnMount(mountPointPath string) error {
err := fuse.Unmount(mountPointPath)
if err != nil {
return err
}
return nil
}
// Root initialize the root directory.
func (f *FS) Root() (fs.Node, error) {
dir := fsnode.NewDir()
structMap := structs.Map(f.UserStructRef)
dir.Entries = f.createEntries(structMap, []string{})
return dir, nil
}
// createEntries creates a map of directories and files a directory have.
func (f *FS) createEntries(structMap map[string]any, currentPath []string) map[string]any {
entries := map[string]any{}
for key, val := range structMap {
if reflect.TypeOf(val).Kind() == reflect.Map {
dir := fsnode.NewDir()
dir.Entries = f.createEntries(val.(map[string]any), append(currentPath, key))
entries[key] = dir
} else {
filePath := make([]string, len(currentPath))
copy(filePath, currentPath)
content := []byte(fmt.Sprintln(reflect.ValueOf(val)))
file := fsnode.NewFile(key, filePath, len(content), f.UserStructRef)
entries[key] = file
}
}
return entries
}