-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
70 lines (61 loc) · 1.14 KB
/
util.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
package jqx
import (
"encoding/json"
"fmt"
"io/fs"
"testing/fstest"
)
type failError string
func (f failError) Error() string { return string(f) }
func must[T any](val T, err error) T {
if err != nil {
panic(err)
}
return val
}
func failif(err error, format string, args ...any) {
if err == nil {
return
}
s := fmt.Sprintf(format, args...)
s = fmt.Sprintf("error while %s: %v", s, err)
panic(failError(s))
}
func catch[T error](rt *error) {
err := recover()
switch err := err.(type) {
case nil:
case T:
*rt = err
default:
panic(err)
}
}
func getMarshaler(tab bool, str bool) func(v any) ([]byte, error) {
f := json.Marshal
if tab {
f = func(v any) ([]byte, error) {
return json.MarshalIndent(v, "", "\t")
}
}
if str {
oldf := f
f = func(v any) ([]byte, error) {
if v, ok := v.(string); ok {
return []byte(v), nil
}
return oldf(v)
}
}
return f
}
func toFS(m map[string]any, marshaler func(any) ([]byte, error)) fs.FS {
if marshaler == nil {
marshaler = getMarshaler(false, true)
}
rt := fstest.MapFS{}
for k, v := range m {
rt[k] = &fstest.MapFile{Data: must(marshaler(v))}
}
return rt
}