Home

overlay @5f001da59ecdb1f8937d2817b86b9e83db1dd554 - refs - log -
-
https://git.jolheiser.com/overlay.git
Overlay FS
overlay / overlay.go
- raw
 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
package overlay

import (
	"io/fs"
	"os"
	"path"
)

// FS is an overlay File System
type FS struct {
	fs      fs.FS
	root    string
	doCache bool
	cache   map[string]bool
}

func (f *FS) apn(name string) string {
	return path.Join(f.root, name)
}

func (f *FS) exists(name string) bool {
	if has, ok := f.cache[name]; ok && f.doCache {
		return has
	}
	_, err := os.Stat(f.apn(name))
	if err != nil {
		f.cache[name] = false
		return false
	}
	f.cache[name] = true
	return true
}

// Open opens an fs.File, preferring disk
func (f *FS) Open(name string) (fs.File, error) {
	if f.exists(name) {
		return os.Open(f.apn(name))
	}
	return f.fs.Open(name)
}

// Option is a functional option for an FS
type Option func(*FS) error

// New returns a new FS
func New(root string, fs fs.FS, opts ...Option) (*FS, error) {
	x := &FS{
		fs:      fs,
		root:    root,
		doCache: true,
		cache:   make(map[string]bool),
	}

	for _, opt := range opts {
		if err := opt(x); err != nil {
			return x, err
		}
	}

	return x, nil
}

// WithSub sets a fs.Sub for an FS
func WithSub(sub string) Option {
	return func(x *FS) (err error) {
		x.fs, err = fs.Sub(x.fs, sub)
		return
	}
}

// WithCaching sets a caching mode for an FS
// Caching avoids subsequent os.Stat to determine if a file exists on disk
// See bench.txt for differences in usage
func WithCaching(doCache bool) Option {
	return func(x *FS) error {
		x.doCache = doCache
		return nil
	}
}