/
loader.go
197 lines (165 loc) · 4.13 KB
/
loader.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package load
import (
"encoding/json"
"fmt"
"image"
"image/draw"
"io/fs"
"io/ioutil"
"os"
"path"
"runtime"
"strings"
"github.com/golang/freetype/truetype"
"github.com/jakubDoka/sterr"
"golang.org/x/image/font"
)
// errors
var (
ErrNotOnDisc = sterr.New("%s file not found on disc")
)
// AppData returns AppData access, the root is usually the name of your app
func AppData(root string) (Util, error) {
ad, err := AppDataDir()
return Util{
Loader: OSFS{},
Root: path.Join(ad, root),
}, err
}
// AppDataDir returns directory where the app data is located
func AppDataDir() (string, error) {
var home string
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
} else {
home = os.Getenv("HOME")
}
if home == "" {
home = os.Getenv("APPDATA")
if home == "" {
return "", sterr.New("unable to optain AppData directory path")
}
} else {
home = path.Join(home, "AppData", "Roaming")
}
return home, nil
}
// Util brings some utility for Loader, if you specify root
// it will be prepended to path you input
type Util struct {
Loader
Root string
}
// OS is default os loader
var OS = Util{Loader: OSFS{}}
// Json unmarshal-s json from given path to dest
func (l Util) Json(p string, dest interface{}) error {
bts, err := l.ReadFile(l.path(p))
if err != nil {
return err
}
return json.Unmarshal(bts, dest)
}
// Save json saves the json representation of given value to disk
func (l Util) SaveJson(p string, value interface{}) error {
bts, err := json.Marshal(value)
if err != nil {
return err
}
return ioutil.WriteFile(l.path(p), bts, os.ModePerm)
}
// LoadTTF loads TTF file into font.Face
func (l Util) LoadTTF(p string, size float64) (font.Face, error) {
bytes, err := l.ReadFile(l.path(p))
if err != nil {
return nil, ErrNotOnDisc.Args("ttf").Wrap(err)
}
font, err := truetype.Parse(bytes)
if err != nil {
return nil, err
}
return truetype.NewFace(font, &truetype.Options{
Size: size,
GlyphCacheEntries: 1,
}), nil
}
// LoadImage loads image from disk
func (l Util) LoadImage(p string) (*image.NRGBA, error) {
imgFile, err := l.Open(l.path(p))
if err != nil {
return nil, ErrNotOnDisc.Args("image").Wrap(err)
}
img, _, err := image.Decode(imgFile)
if err != nil {
return nil, fmt.Errorf("failed to decode %q: %v", p, err)
}
var res *image.NRGBA
switch v := img.(type) {
case *image.NRGBA:
res = v
default:
res = image.NewNRGBA(v.Bounds())
draw.Draw(res, res.Rect, img, img.Bounds().Min, 0)
}
return res, nil
}
// Walk calls fs.WalkDir on Loader
func (l Util) Walk(root string, fn func(path string, d fs.DirEntry, err error) error) {
fs.WalkDir(l, l.path(root), fn)
}
// List lists all paths in given directory. If rec == true, function will go recursively. If ext == ""
// they any extencion is valid, ext does not include dot ("go" not ".go")
func (l Util) List(root string, buff []string, rec bool, ext string) (r []string, err error) {
r = buff
entries, err := l.ReadDir(l.path(root))
if err != nil {
return
}
for _, e := range entries {
p := path.Join(root, e.Name())
if e.IsDir() {
if rec {
r, err = l.List(p, r, true, ext)
if err != nil {
return
}
}
} else {
idx := strings.LastIndex(e.Name(), ".")
if idx == -1 {
if ext == "" {
r = append(r, p)
}
} else if ext == "" || e.Name()[idx+1:] == ext {
r = append(r, p)
}
}
}
return
}
func (l Util) path(base string) string {
return path.Join(l.Root, base)
}
// Loader can be a OSFS or embed.FS, so writing generic
// asset loading where it does not matter where you load from
type Loader interface {
fs.ReadDirFS
ReadFile(name string) ([]byte, error)
}
// OSFS uses os as source of data
type OSFS struct{}
// Open implements fs.FS interface
func (o OSFS) Open(path string) (fs.File, error) {
return os.Open(path)
}
// ReadFile implements AssetLoader interface
func (o OSFS) ReadFile(path string) ([]byte, error) {
return ioutil.ReadFile(path)
}
// ReadDir implements fs.ReadDirFS interface
func (o OSFS) ReadDir(path string) ([]fs.DirEntry, error) {
return os.ReadDir(path)
}