forked from k1LoW/runn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dump.go
93 lines (86 loc) · 1.7 KB
/
dump.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
package runn
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"github.com/goccy/go-json"
)
const dumpRunnerKey = "dump"
type dumpRunner struct {
operator *operator
}
type dumpRequest struct {
expr string
out string
}
func newDumpRunner(o *operator) (*dumpRunner, error) {
return &dumpRunner{
operator: o,
}, nil
}
func (rnr *dumpRunner) Run(ctx context.Context, r *dumpRequest) error {
var out io.Writer
store := rnr.operator.store.toMap()
store[storeIncludedKey] = rnr.operator.included
store[storePreviousKey] = rnr.operator.store.previous()
store[storeCurrentKey] = rnr.operator.store.latest()
if r.out == "" {
out = rnr.operator.stdout
} else {
p, err := EvalExpand(r.out, store)
if err != nil {
return err
}
switch pp := p.(type) {
case string:
if !filepath.IsAbs(pp) {
pp = filepath.Join(filepath.Dir(rnr.operator.bookPath), pp)
}
f, err := os.Create(pp)
if err != nil {
return err
}
out = f
default:
return fmt.Errorf("invalid dump out: %v", pp)
}
}
v, err := Eval(r.expr, store)
if err != nil {
return err
}
switch vv := v.(type) {
case string:
if _, err := fmt.Fprint(out, vv); err != nil {
return err
}
case []byte:
// ex. screenshot on CDP
if _, err := out.Write(vv); err != nil {
return err
}
default:
if reflect.ValueOf(v).Kind() == reflect.Func {
if _, err := fmt.Fprint(out, storeFuncValue); err != nil {
return err
}
} else {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprint(out, string(b)); err != nil {
return err
}
}
}
if r.out == "" {
if _, err := fmt.Fprint(out, "\n"); err != nil {
return err
}
}
return nil
}