-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
66 lines (56 loc) · 1.04 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
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 {
return func(v any) []byte {
if str {
if v, ok := v.(string); ok {
return []byte(v)
}
}
if tab {
return must(json.MarshalIndent(v, "", "\t"))
}
return must(json.Marshal(v))
}
}
func toFS(m map[string]any, marshaler func(any) []byte) fs.FS {
if marshaler == nil {
marshaler = getMarshaler(false, true)
}
rt := fstest.MapFS{}
for k, v := range m {
rt[k] = &fstest.MapFile{Data: marshaler(v)}
}
return rt
}