From e8b8fb8d99535234ddc82ff7f2b1c8b7ba0f622c Mon Sep 17 00:00:00 2001 From: Alix Bott Date: Mon, 26 Jul 2021 18:47:17 +0200 Subject: [PATCH] Check command and error details (#29) * add check command to verify validity of a script * add details field to /script api responses in case of an error, with a url to numscript playground showing the formatted error --- api/http.go | 17 ++++++++++++++++- cmd/root.go | 29 ++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/api/http.go b/api/http.go index 2e4fec944b..5a785cb1c0 100644 --- a/api/http.go +++ b/api/http.go @@ -3,6 +3,10 @@ package api import ( "context" _ "embed" + "encoding/base64" + "encoding/json" + "fmt" + "log" "strings" "github.com/gin-contrib/cors" @@ -118,7 +122,18 @@ func NewHttpAPI(lc fx.Lifecycle, resolver *ledger.Resolver) *HttpAPI { } if err != nil { - res["err"] = err.Error() + err_str := err.Error() + err_str = strings.ReplaceAll(err_str, "\n", "\r\n") + payload, err := json.Marshal(gin.H{ + "error": err_str, + }) + if err != nil { + log.Fatal(err) + } + payload_b64 := base64.StdEncoding.EncodeToString([]byte(payload)) + link := fmt.Sprintf("https://play.numscript.org/?payload=%v", payload_b64) + res["err"] = err_str + res["details"] = link } c.JSON(200, res) diff --git a/cmd/root.go b/cmd/root.go index 4993a3c20c..61c3c5abcf 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -15,6 +15,7 @@ import ( "github.com/numary/ledger/config" "github.com/numary/ledger/ledger" "github.com/numary/ledger/storage" + "github.com/numary/machine/script/compiler" "github.com/spf13/cobra" "github.com/spf13/viper" "go.uber.org/fx" @@ -91,7 +92,7 @@ func Execute() { }, }) - script := &cobra.Command{ + script_exec := &cobra.Command{ Use: "exec [ledger] [script]", Args: cobra.ExactArgs(2), Run: func(cmd *cobra.Command, args []string) { @@ -144,18 +145,40 @@ func Execute() { log.Fatal(err) } if result.Ok { - fmt.Println("Script ran successfully 👍") + fmt.Println("Script ran successfully ✅") } else { log.Fatal(result.Err) } }, } + script_check := &cobra.Command{ + Use: "check [script]", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + config.Init() + + b, err := ioutil.ReadFile(args[0]) + + if err != nil { + log.Fatal(err) + } + + _, err = compiler.Compile(string(b)) + if err != nil { + log.Fatal(err) + } else { + fmt.Println("Script is correct ✅") + } + }, + } + root.AddCommand(server) root.AddCommand(conf) root.AddCommand(UICmd) root.AddCommand(store) - root.AddCommand(script) + root.AddCommand(script_exec) + root.AddCommand(script_check) if err := root.Execute(); err != nil { fmt.Fprintln(os.Stderr, err)