-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathresources.go
321 lines (272 loc) · 6.48 KB
/
resources.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Package resources provides unfancy resources embedding with Go.
package resources
import (
"bytes"
"fmt"
"go/format"
"io"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
// File mimicks the os.File and http.File interface.
type File interface {
io.Reader
Stat() (os.FileInfo, error)
}
// New creates a new Package.
func New() *Package {
return &Package{
Config: Config{
Pkg: "resources",
Var: "FS",
Declare: true,
},
Files: make(map[string]File),
}
}
// Config defines some details about the output file
type Config struct {
Pkg string // Pkg holds the package name
Var string // Var holds the variable name for the virtual filesystem
Tag string // Tag may hold an optional build tag, unless empty
Declare bool // Declare controls if the Var should be declared as well
Format bool // Format controls, whether gofmt should be applied to the output
}
// A Package describes a collection of files and how they should be tranformed
// to an output.
type Package struct {
Config
Files map[string]File
}
// Add a file to the package at the give path.
func (p *Package) Add(path string, file File) error {
path = filepath.ToSlash(path)
p.Files[path] = file
return nil
}
// AddFile is a helper function that adds a file into the package.
func (p *Package) AddFile(path string, file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
return p.Add(path, f)
}
// AddFiles is a helper function that recursively adds files to the package.
func (p *Package) AddFiles(trimPath string, path string) (int, error) {
var n int
err := filepath.Walk(path, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
f, err := os.Open(filePath)
if err != nil {
return err
}
n++
return p.Add(strings.TrimPrefix(filePath, trimPath), f)
})
return n, err
}
// Build compiles the package and writes it into an io.Writer.
func (p *Package) Build(out io.Writer) error {
return pkg.Execute(out, p)
}
// Write builds the package (via Build) and writes the output the the file
// given by the path argument.
func (p *Package) Write(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() {
err := f.Close()
if err != nil {
log.Panicf("Failed to close file: %s", err)
}
}()
if !p.Format {
return p.Build(f)
}
buf := &bytes.Buffer{}
if e := p.Build(buf); e != nil {
return e
}
fmted, e := format.Source(buf.Bytes())
if e != nil {
return e
}
_, e = f.Write(fmted)
return e
}
var (
// Template
pkg *template.Template
// BlockWidth allows to adjust the number of bytes per line in the generated file
BlockWidth = 12
)
func reader(input io.Reader, indent int) (string, error) {
var (
buff bytes.Buffer
err error
curblock = 0
linebreak = "\n" + strings.Repeat("\t", indent)
)
b := make([]byte, BlockWidth)
for n, e := input.Read(b); e == nil; n, e = input.Read(b) {
for i := 0; i < n; i++ {
_, e = fmt.Fprintf(&buff, "0x%02x,", b[i])
if e != nil {
err = e
break
}
curblock++
if curblock < BlockWidth {
buff.WriteRune(' ')
continue
}
buff.WriteString(linebreak)
curblock = 0
}
}
return buff.String(), err
}
func init() {
pkg = template.Must(template.New("file").Funcs(template.FuncMap{"reader": reader}).Parse(fileTemplate))
pkg = template.Must(pkg.New("pkg").Parse(pkgTemplate))
}
const fileTemplate = `File{
data: []byte{
{{ reader . 5 }}
},
fi: FileInfo{
name: "{{ .Stat.Name }}",
size: {{ .Stat.Size }},
modTime: time.Unix(0, {{ .Stat.ModTime.UnixNano }}),
isDir: {{ .Stat.IsDir }},
},
}`
const pkgTemplate = `{{ if .Tag }}// +build {{ .Tag }}
{{ end }}// Package {{ .Pkg }} is generated by github.com/omeid/go-resources
package {{ .Pkg }}
import (
"bytes"
"errors"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
// FileSystem is an http.FileSystem implementation.
type FileSystem struct {
files map[string]File
}
// String returns the content of the file as string.
func (fs *FileSystem) String(name string) (string, bool) {
if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
strings.Contains(name, "\x00") {
return "", false
}
file, ok := fs.files[name]
if !ok {
return "", false
}
return string(file.data), true
}
// Open implements http.FileSystem.Open
func (fs *FileSystem) Open(name string) (http.File, error) {
if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
strings.Contains(name, "\x00") {
return nil, errors.New("http: invalid character in file path")
}
file, ok := fs.files[name]
if !ok {
files := []os.FileInfo{}
for path, file := range fs.files {
if strings.HasPrefix(path, name) {
fi := file.fi
files = append(files, &fi)
}
}
if len(files) == 0 {
return nil, os.ErrNotExist
}
//We have a directory.
return &File{
fi: FileInfo{
isDir: true,
files: files,
}}, nil
}
file.Reader = bytes.NewReader(file.data)
return &file, nil
}
// File implements http.File
type File struct {
*bytes.Reader
data []byte
fi FileInfo
}
// Close is a noop-closer.
func (f *File) Close() error {
return nil
}
// Readdir implements http.File.Readdir
func (f *File) Readdir(_ int) ([]os.FileInfo, error) {
return nil, os.ErrNotExist
}
// Stat implements http.Stat.Readdir
func (f *File) Stat() (os.FileInfo, error) {
return &f.fi, nil
}
// FileInfo implements the os.FileInfo interface.
type FileInfo struct {
name string
size int64
mode os.FileMode
modTime time.Time
isDir bool
sys interface{}
files []os.FileInfo
}
// Name implements os.FileInfo.Name
func (f *FileInfo) Name() string {
return f.name
}
// Size implements os.FileInfo.Size
func (f *FileInfo) Size() int64 {
return f.size
}
// Mode implements os.FileInfo.Mode
func (f *FileInfo) Mode() os.FileMode {
return f.mode
}
// ModTime implements os.FileInfo.ModTime
func (f *FileInfo) ModTime() time.Time {
return f.modTime
}
// IsDir implements os.FileInfo.IsDir
func (f *FileInfo) IsDir() bool {
return f.isDir
}
// Readdir implements os.FileInfo.Readdir
func (f *FileInfo) Readdir(_ int) ([]os.FileInfo, error) {
return f.files, nil
}
// Sys returns the underlying value.
func (f *FileInfo) Sys() interface{} {
return f.sys
}
{{ if .Declare }}var {{ .Var }} *FileSystem{{ end }}
func init() {
{{ .Var }} = &FileSystem{
files: map[string]File{
{{range $path, $file := .Files }}"/{{ $path }}": {{ template "file" $file }},{{ end }}
},
}
}
`