-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
125 lines (105 loc) · 2.54 KB
/
main.go
File metadata and controls
125 lines (105 loc) · 2.54 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"github.com/formancehq/numscript"
"github.com/spf13/cobra"
)
var Version string
func version() string {
if Version == "" {
return "dev"
} else {
return Version
}
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Shows the app version",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
fmt.Print(version())
},
}
type RunInputOpts struct {
Script string `json:"script"`
Variables map[string]string `json:"variables"`
Meta numscript.AccountsMetadata `json:"metadata"`
Balances numscript.Balances `json:"balances"`
FeatureFlags map[string]struct{} `json:"featureFlags"`
}
func run() {
opt := RunInputOpts{
Variables: make(map[string]string),
Meta: make(numscript.AccountsMetadata),
Balances: make(numscript.Balances),
FeatureFlags: make(map[string]struct{}),
}
bytes, err := io.ReadAll(os.Stdin)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
panic(err)
}
err = json.Unmarshal(bytes, &opt)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
panic(err)
}
parsedResult := numscript.Parse(opt.Script)
errors := parsedResult.GetParsingErrors()
if len(errors) != 0 {
os.Stderr.Write([]byte(numscript.ParseErrorsToString(errors, opt.Script)))
panic(fmt.Errorf("parsing errors"))
}
result, err := parsedResult.RunWithFeatureFlags(
context.Background(),
opt.Variables,
numscript.StaticStore{
Balances: opt.Balances,
Meta: opt.Meta,
},
opt.FeatureFlags,
)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
panic(err)
}
out, err := json.Marshal(result)
if err != nil {
os.Stderr.Write([]byte(err.Error()))
panic(err)
}
os.Stdout.Write(out)
}
var runCmd = &cobra.Command{
Use: "run",
Short: "Execute a numscript",
Long: "Execute a numscript using the balances, the current metadata, and the variables values as input. Also accept feature flags to enable experimental features.",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}
var rootCmd = &cobra.Command{
Use: "numscript",
Short: "Numscript CLI",
Long: "Numscript CLI",
Version: version(),
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
},
}
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Fprintf(os.Stderr, "Exception: %v\n", err)
os.Exit(1)
}
}()
rootCmd.SetVersionTemplate(rootCmd.Version)
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(runCmd)
rootCmd.Execute()
}