|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + sparkscan "github.com/refrakts/sparkscan-api-go" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + |
| 10 | + "github.com/refrakts/sparkscan-cli/cmd/address" |
| 11 | + "github.com/refrakts/sparkscan-cli/cmd/stats" |
| 12 | + "github.com/refrakts/sparkscan-cli/cmd/token" |
| 13 | + "github.com/refrakts/sparkscan-cli/cmd/tx" |
| 14 | + "github.com/refrakts/sparkscan-cli/cmd/version" |
| 15 | + "github.com/refrakts/sparkscan-cli/cmdutil" |
| 16 | + "github.com/refrakts/sparkscan-cli/output" |
| 17 | +) |
| 18 | + |
| 19 | +// NewRootCmd creates the root sparkscan command. |
| 20 | +func NewRootCmd(versionStr string) *cobra.Command { |
| 21 | + root := &cobra.Command{ |
| 22 | + Use: "sparkscan", |
| 23 | + Short: "CLI for the Sparkscan API", |
| 24 | + Long: "A command-line interface for the Sparkscan blockchain explorer API.\n\nQuery addresses, tokens, transactions, and network statistics on the Spark network.", |
| 25 | + SilenceUsage: true, |
| 26 | + SilenceErrors: true, |
| 27 | + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { |
| 28 | + if cmd.Annotations != nil && cmd.Annotations["skipClient"] == "true" { |
| 29 | + return nil |
| 30 | + } |
| 31 | + |
| 32 | + apiKey, _ := cmd.Flags().GetString("api-key") |
| 33 | + if apiKey == "" { |
| 34 | + apiKey = os.Getenv("SPARKSCAN_API_KEY") |
| 35 | + } |
| 36 | + |
| 37 | + baseURL, _ := cmd.Flags().GetString("base-url") |
| 38 | + |
| 39 | + var opts []sparkscan.Option |
| 40 | + if apiKey != "" { |
| 41 | + opts = append(opts, sparkscan.WithAPIKey(apiKey)) |
| 42 | + } |
| 43 | + |
| 44 | + client, err := sparkscan.NewClient(baseURL, opts...) |
| 45 | + if err != nil { |
| 46 | + return fmt.Errorf("creating client: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + cmdutil.SetClient(cmd, client) |
| 50 | + return nil |
| 51 | + }, |
| 52 | + } |
| 53 | + |
| 54 | + root.PersistentFlags().String("api-key", "", "Sparkscan API key (overrides SPARKSCAN_API_KEY)") |
| 55 | + root.PersistentFlags().String("base-url", "https://api.sparkscan.io", "API base URL") |
| 56 | + root.PersistentFlags().String("network", "MAINNET", "Network: MAINNET or REGTEST") |
| 57 | + output.AddFormatFlag(root) |
| 58 | + |
| 59 | + root.AddCommand(address.NewCmd()) |
| 60 | + root.AddCommand(token.NewCmd()) |
| 61 | + root.AddCommand(tx.NewCmd()) |
| 62 | + root.AddCommand(stats.NewCmd()) |
| 63 | + root.AddCommand(version.NewCmd(versionStr)) |
| 64 | + |
| 65 | + return root |
| 66 | +} |
| 67 | + |
| 68 | +// Execute runs the CLI. |
| 69 | +func Execute(version, commit, date string) { |
| 70 | + versionStr := fmt.Sprintf("%s (commit: %s, built: %s)", version, commit, date) |
| 71 | + root := NewRootCmd(versionStr) |
| 72 | + |
| 73 | + if err := root.Execute(); err != nil { |
| 74 | + fmt.Fprintln(os.Stderr, err) |
| 75 | + os.Exit(1) |
| 76 | + } |
| 77 | +} |
0 commit comments