-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrun.go
225 lines (190 loc) · 5.77 KB
/
run.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
package cmd
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"github.com/formancehq/numscript/internal/ansi"
"github.com/formancehq/numscript/internal/interpreter"
"github.com/formancehq/numscript/internal/parser"
"github.com/spf13/cobra"
)
const (
OutputFormatPretty = "pretty"
OutputFormatJson = "json"
)
var runVariablesOpt string
var runBalancesOpt string
var runMetaOpt string
var runRawOpt string
var runStdinFlag bool
var runOutFormatOpt string
var overdraftFeatureFlag bool
var oneOfFeatureFlag bool
var accountInterpolationFlag bool
var midScriptFunctionCallFeatureFlag bool
type inputOpts struct {
Script string `json:"script"`
Variables map[string]string `json:"variables"`
Meta interpreter.AccountsMetadata `json:"metadata"`
Balances interpreter.Balances `json:"balances"`
}
func (o *inputOpts) fromRaw() {
if runRawOpt == "" {
return
}
err := json.Unmarshal([]byte(runRawOpt), o)
if err != nil {
panic(err)
}
}
func (o *inputOpts) fromStdin() {
if !runStdinFlag {
return
}
bytes, err := io.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
err = json.Unmarshal(bytes, o)
if err != nil {
panic(err)
}
}
func (o *inputOpts) fromOptions(path string) {
if path != "" {
numscriptContent, err := os.ReadFile(path)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
return
}
o.Script = string(numscriptContent)
}
if runBalancesOpt != "" {
content, err := os.ReadFile(runBalancesOpt)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
return
}
json.Unmarshal(content, &o.Balances)
}
if runMetaOpt != "" {
content, err := os.ReadFile(runMetaOpt)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
return
}
json.Unmarshal(content, &o.Meta)
}
if runVariablesOpt != "" {
content, err := os.ReadFile(runVariablesOpt)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
return
}
json.Unmarshal(content, &o.Variables)
}
}
func run(path string) {
opt := inputOpts{
Variables: make(map[string]string),
Meta: make(interpreter.AccountsMetadata),
Balances: make(interpreter.Balances),
}
opt.fromRaw()
opt.fromOptions(path)
opt.fromStdin()
parseResult := parser.Parse(opt.Script)
if len(parseResult.Errors) != 0 {
os.Stderr.Write([]byte(parser.ParseErrorsToString(parseResult.Errors, opt.Script)))
os.Exit(1)
}
featureFlags := map[string]struct{}{}
if overdraftFeatureFlag {
featureFlags[interpreter.ExperimentalOverdraftFunctionFeatureFlag] = struct{}{}
}
if oneOfFeatureFlag {
featureFlags[interpreter.ExperimentalOneofFeatureFlag] = struct{}{}
}
if accountInterpolationFlag {
featureFlags[interpreter.ExperimentalAccountInterpolationFlag] = struct{}{}
}
if midScriptFunctionCallFeatureFlag {
featureFlags[interpreter.ExperimentalMidScriptFunctionCall] = struct{}{}
}
result, err := interpreter.RunProgram(context.Background(), parseResult.Value, opt.Variables, interpreter.StaticStore{
Balances: opt.Balances,
Meta: opt.Meta,
}, featureFlags)
if err != nil {
rng := err.GetRange()
os.Stderr.Write([]byte(err.Error()))
if rng.Start != rng.End {
os.Stderr.Write([]byte("\n"))
os.Stderr.Write([]byte(err.GetRange().ShowOnSource(parseResult.Source)))
}
os.Exit(1)
return
}
switch runOutFormatOpt {
case OutputFormatJson:
showJson(result)
case OutputFormatPretty:
showPretty(result)
default:
// TODO handle err
panic("Invalid option: " + runBalancesOpt)
}
}
func showJson(result *interpreter.ExecutionResult) {
out, err := json.Marshal(result)
if err != nil {
// TODO handle err
panic(err)
}
os.Stdout.Write(out)
}
func showPretty(result *interpreter.ExecutionResult) {
fmt.Println(ansi.ColorCyan("Postings:"))
postingsJson, err := json.MarshalIndent(result.Postings, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(postingsJson))
fmt.Println()
fmt.Println(ansi.ColorCyan("Meta:"))
txMetaJson, err := json.MarshalIndent(result.Metadata, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(txMetaJson))
}
func getRunCmd() *cobra.Command {
cmd := cobra.Command{
Use: "run",
Short: "Evaluate a numscript file",
Long: "Evaluate a numscript file, using the balances, the current metadata and the variables values as input.",
Run: func(cmd *cobra.Command, args []string) {
var path string
if len(args) > 0 {
path = args[0]
}
run(path)
},
}
// Input args
cmd.Flags().StringVarP(&runVariablesOpt, "variables", "v", "", "Path of a json file containing the variables")
cmd.Flags().StringVarP(&runBalancesOpt, "balances", "b", "", "Path of a json file containing the balances")
cmd.Flags().StringVarP(&runMetaOpt, "meta", "m", "", "Path of a json file containing the accounts metadata")
cmd.Flags().StringVarP(&runRawOpt, "raw", "r", "", "Raw json input containing script, variables, balances, metadata")
cmd.Flags().BoolVar(&runStdinFlag, "stdin", false, "Take input from stdin (same format as the --raw option)")
// Feature flag
cmd.Flags().BoolVar(&overdraftFeatureFlag, interpreter.ExperimentalOverdraftFunctionFeatureFlag, false, "enables the experimental overdraft() function")
cmd.Flags().BoolVar(&oneOfFeatureFlag, interpreter.ExperimentalOneofFeatureFlag, false, "enable the experimental oneof combinator")
cmd.Flags().BoolVar(&accountInterpolationFlag, interpreter.ExperimentalAccountInterpolationFlag, false, "enables an account interpolation syntax, e.g. @users:$id:pending")
cmd.Flags().BoolVar(&midScriptFunctionCallFeatureFlag, interpreter.ExperimentalMidScriptFunctionCall, false, "allows to use function call as expression, and to use any expression when definining variables")
// Output options
cmd.Flags().StringVar(&runOutFormatOpt, "output-format", OutputFormatPretty, "Set the output format. Available options: pretty, json.")
return &cmd
}