|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/manifoldco/promptui" |
| 9 | + "github.com/onflow/flow-go-sdk/client" |
| 10 | + "github.com/spf13/viper" |
| 11 | + "google.golang.org/grpc/codes" |
| 12 | +) |
| 13 | + |
| 14 | +// SilentErr is silent error passed through |
| 15 | +var SilentErr = errors.New("SilentErr") |
| 16 | + |
| 17 | +// PromptURL enters discovery api url if missing |
| 18 | +func PromptURL() { |
| 19 | + |
| 20 | + validate := func(input string) error { |
| 21 | + /*_, err := strconv.ParseFloat(input, 64) |
| 22 | + if err != nil { |
| 23 | + return errors.New("Invalid url") |
| 24 | + }*/ |
| 25 | + return nil |
| 26 | + } |
| 27 | + |
| 28 | + prompt := promptui.Prompt{ |
| 29 | + Label: "Enter Flow emulator discovery API URL", |
| 30 | + Validate: validate, |
| 31 | + } |
| 32 | + |
| 33 | + result, err := prompt.Run() |
| 34 | + |
| 35 | + if err != nil { |
| 36 | + fmt.Printf("Prompt failed %v\n", err) |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + viper.Set("APIURL", result) |
| 41 | + viper.WriteConfigAs("./config.yaml") |
| 42 | +} |
| 43 | + |
| 44 | +// HandleError main error handler for commands |
| 45 | +func HandleError(err error) { |
| 46 | + if err != SilentErr { |
| 47 | + // check if error is grpc error |
| 48 | + rpcError := client.RPCError{} |
| 49 | + if errors.As(err, &rpcError) { |
| 50 | + handleGrpcError(rpcError) |
| 51 | + } else { // unhandeled error - can be improved |
| 52 | + fmt.Printf("\n\033[31mUnhandeled Error: %s\033[0m\n\n", err) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + os.Exit(1) |
| 57 | +} |
| 58 | + |
| 59 | +func handleGrpcError(rpcError client.RPCError) { |
| 60 | + switch rpcError.GRPCStatus().Code() { |
| 61 | + case codes.InvalidArgument: |
| 62 | + fmt.Printf("\n\033[31mInvalid Arguments: %s\033[0m\n\n", rpcError.GRPCStatus().Message()) |
| 63 | + case codes.Unavailable: |
| 64 | + fmt.Printf("\nConnection to Flow Emulator was not successful, please make sure your api url is correct.\n\nSet it by using: flow config \n") |
| 65 | + fmt.Printf("\n\033[31mConnection Error: %s\033[0m\n\n", rpcError.GRPCStatus().Message()) |
| 66 | + PromptURL() |
| 67 | + default: |
| 68 | + fmt.Printf("\n\033[31mUnhandeled Error: %s\033[0m\n\n", rpcError.GRPCStatus().Err()) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +// InitConfig initialize config for viper |
| 73 | +func InitConfig() { |
| 74 | + viper.SetConfigName("config") |
| 75 | + viper.SetConfigType("yaml") |
| 76 | + viper.AddConfigPath(".") |
| 77 | + viper.SetDefault("APIURL", "localhost:3569") |
| 78 | + |
| 79 | + if err := viper.ReadInConfig(); err != nil { |
| 80 | + if _, ok := err.(viper.ConfigFileNotFoundError); ok { |
| 81 | + fmt.Println("ERROR not found") |
| 82 | + } else { |
| 83 | + // Config file was found but another error was produced |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments