-
Notifications
You must be signed in to change notification settings - Fork 0
/
lang.go
97 lines (84 loc) · 2.19 KB
/
lang.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
package egress
import (
"encoding/json"
"encoding/xml"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
"github.com/peter-mount/go-script/calculator"
"github.com/peter-mount/go-script/script"
"github.com/peter-mount/piweather.center/config/util/amqp"
"gopkg.in/yaml.v3"
)
type Script struct {
Pos lexer.Position
//Locations []*calc.Location `parser:"(@@)*"` // Share the same from calculator
Amqp []*amqp.Amqp `parser:"(@@)?"`
Actions []*Action `parser:"(@@)+"`
state *State
}
func (s *Script) State() *State {
return s.state
}
func (s *Script) merge(b *Script) (*Script, error) {
if s == nil {
return b, nil
}
s.Amqp = append(s.Amqp, b.Amqp...)
s.Actions = append(s.Actions, b.Actions...)
s.state.merge(b.state)
return s, nil
}
type Action struct {
Pos lexer.Position
Metric *Metric `parser:"( @@ )"`
}
// Metric on receipt
type Metric struct {
Pos lexer.Position
Metrics []string `parser:"'metric' (@String | 'in' '(' @String (',' @String)* ')' )"`
Statement *script.Statements `parser:"(@@)?"`
Publish []*Publish `parser:"'publish' (@@)+"`
}
type Publish struct {
Pos lexer.Position
Amqp string `parser:"( 'amqp' @String"`
Console bool `parser:"| @'console' )"`
As *PublishType `parser:"(@@)?"`
}
type PublishType struct {
Pos lexer.Position
Bytes bool `parser:"'as' ( @'bytes'"`
Json bool `parser:"| @'json'"`
String bool `parser:"| @('string' | 'text')"`
Xml bool `parser:"| @'xml'"`
Yaml bool `parser:"| @'yaml' )"`
}
type Marshaller func(v any) ([]byte, error)
func (p *PublishType) Marshaller() Marshaller {
switch {
// p==nil must be first here as it's valid for PublishType to be nil
case p == nil, p.Bytes, p.String:
return bytes
case p.Json:
return json.Marshal
case p.Xml:
return xml.Marshal
case p.Yaml:
return yaml.Marshal
default:
return func(_ any) ([]byte, error) {
return nil, participle.Errorf(p.Pos, "invalid type")
}
}
}
func bytes(v any) ([]byte, error) {
v1 := calculator.GetValue(v)
if b, ok := v1.([]byte); ok {
return b, nil
}
s, err := calculator.GetString(v1)
if err != nil {
return nil, err
}
return []byte(s), err
}