Debian Codegraph @

osfs/os_js.go

raw symbols SCIP
1 //go:build js
2
3 package osfs
4
5 import (
6 "path/filepath"
7 "strings"
8
9 "github.com/go-git/go-billy/v6"
10 "github.com/go-git/go-billy/v6/helper/chroot"
11 "github.com/go-git/go-billy/v6/memfs"
12 )
13
14 // globalMemFs is the global memory fs
15 var globalMemFs = memfs.New()
16
17 // Default Filesystem representing the root of in-memory filesystem for a
18 // js/wasm environment.
19 var Default = memfs.New()
20
21 // New returns a new OS filesystem rooted at baseDir, backed by the
22 // js/wasm in-memory filesystem.
23 func New(baseDir string, opts ...Option) billy.Filesystem {
24 o := &options{}
25 for _, opt := range opts {
26 opt(o)
27 }
28
29 return newBoundOS(baseDir)
30 }
31
32 // BoundOS is a fs implementation based on the js/wasm in-memory filesystem
33 // which is bound to a base dir.
34 type BoundOS struct {
35 billy.Filesystem
36 baseDir string
37 }
38
39 func newBoundOS(d string) billy.Filesystem {
40 baseDir := globalMemFs.Join("/", d)
41 return &BoundOS{
42 Filesystem: chroot.New(globalMemFs, baseDir),
43 baseDir: baseDir,
44 }
45 }
46
47 // Capabilities implements the billy.Capable interface, delegating to the
48 // underlying in-memory filesystem.
49 func (fs *BoundOS) Capabilities() billy.Capability {
50 return billy.Capabilities(fs.Filesystem)
51 }
52
53 // Chroot returns a new BoundOS filesystem, with the base dir set to the
54 // result of joining the provided path with the underlying base dir.
55 func (fs *BoundOS) Chroot(path string) (billy.Filesystem, error) {
56 joined, err := fs.abs(path)
57 if err != nil {
58 return nil, err
59 }
60 return New(joined, WithBoundOS()), nil
61 }
62
63 // Root returns the current base dir of the billy.Filesystem.
64 func (fs *BoundOS) Root() string {
65 return fs.baseDir
66 }
67
68 func (fs *BoundOS) abs(filename string) (string, error) {
69 if filename == "." || filename == "" {
70 return fs.baseDir, nil
71 }
72
73 filename = filepath.ToSlash(filename)
74 filename = filepath.Clean(filename)
75 if strings.HasPrefix(filename, "..") {
76 return "", billy.ErrCrossedBoundary
77 }
78
79 filename = strings.TrimPrefix(filename, string(filepath.Separator))
80 return filepath.Clean(filepath.Join(fs.baseDir, filepath.FromSlash(filename))), nil
81 }
82
83 // WithBoundOS returns the option of using a Bound filesystem OS.
84 func WithBoundOS() Option {
85 return func(o *options) {
86 o.Type = BoundOSFS
87 }
88 }
89
90 // WithMmap is a no-op on js/wasm; the in-memory backing has no fd to
91 // map. The function exists so cross-platform callers can pass the
92 // option without build tags.
93 func WithMmap() Option {
94 return func(o *options) {
95 o.mmap = true
96 }
97 }
98
99 type Option func(*options)
100
101 type options struct {
102 Type
103 mmap bool
104 }
105
106 type Type int
107
108 const (
109 BoundOSFS Type = iota
110 )