Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add cobra cli library #89

Merged
merged 5 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 26 additions & 15 deletions cmd/bursa/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,35 @@
package main

import (
"fmt"
"log/slog"
"os"

"github.com/blinklabs-io/bursa/internal/api"
"github.com/blinklabs-io/bursa/internal/config"
"github.com/blinklabs-io/bursa/internal/logging"
"github.com/spf13/cobra"
)

func apiMain() {
cfg := config.GetConfig()
logger := logging.GetLogger()
// Start API listener
logger.Infof(
"starting API listener on %s:%d",
cfg.Api.ListenAddress,
cfg.Api.ListenPort,
)
if err := api.Start(cfg); err != nil {
logger.Fatalf("failed to start API: %s", err)
}
func apiCommand() *cobra.Command {
apiCommand := cobra.Command{
Use: "api",
Short: "Runs the api",
Run: func(cmd *cobra.Command, args []string) {
cfg := config.GetConfig()
// Start API listener
slog.Info(fmt.Sprintf(
"starting API listener on %s:%d",
cfg.Api.ListenAddress,
cfg.Api.ListenPort,
))
if err := api.Start(cfg); err != nil {
slog.Error("failed to start API: %s", err)
os.Exit(1)
}

// Wait forever
select {}
// Wait forever
select {}
},
}
return &apiCommand
}
102 changes: 37 additions & 65 deletions cmd/bursa/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,80 +15,52 @@
package main

import (
"flag"
"fmt"
"log/slog"
"os"

"github.com/blinklabs-io/bursa/internal/config"
"github.com/blinklabs-io/bursa/internal/logging"
"github.com/blinklabs-io/bursa/internal/consolelog"
"github.com/spf13/cobra"
)

const (
programName = "bursa"
)

func main() {
var appName string
if os.Args == nil {
appName = "bursa"
} else {
appName = os.Args[0]
}
fs := flag.NewFlagSet(appName, flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(
flag.CommandLine.Output(),
"Usage: %s [-h] <subcommand> [args]\n\nSubcommands:\n\n",
appName,
)
fmt.Fprintf(
flag.CommandLine.Output(),
" - %-18s %s\n",
"api",
"run an API server",
)
fmt.Fprintf(
flag.CommandLine.Output(),
" - %-18s %s\n",
"cli",
"run a terminal command",
)
}
if os.Args == nil {
fs.Usage()
os.Exit(1)
}
_ = fs.Parse(os.Args[1:]) // ignore parse errors
globalFlags := struct {
debug bool
}{}

// Load Config
_, err := config.LoadConfig()
if err != nil {
fmt.Printf("Failed to load config: %s\n", err)
os.Exit(1)
rootCmd := &cobra.Command{
Use: programName,
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
},
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Configure default logger
logLevel := slog.LevelInfo
if globalFlags.debug {
logLevel = slog.LevelDebug
}
logger := slog.New(
consolelog.NewHandler(os.Stdout, &slog.HandlerOptions{
Level: logLevel,
}),
)
slog.SetDefault(logger)
},
}
// Configure logging
logging.Setup()
logger := logging.GetLogger()
// Sync logger on exit
defer func() {
if err := logger.Sync(); err != nil {
// ignore error
return
}
}()

var subCommand string
// Parse subcommand
if len(fs.Args()) < 1 {
fs.Usage()
os.Exit(1)
} else {
subCommand = fs.Arg(0)
}
// Global flags
rootCmd.PersistentFlags().BoolVarP(&globalFlags.debug, "debug", "D", false, "enable debug logging")

rootCmd.AddCommand(
newCommand(),
apiCommand(),
)

switch subCommand {
case "api":
apiMain()
case "cli":
cliMain()
default:
fmt.Printf("Unknown subcommand: %s\n", subCommand)
if err := rootCmd.Execute(); err != nil {
// NOTE: we purposely don't display the error, since cobra will have already displayed it
os.Exit(1)
}
}
32 changes: 29 additions & 3 deletions cmd/bursa/cli.go → cmd/bursa/new.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -16,8 +16,34 @@ package main

import (
"github.com/blinklabs-io/bursa/internal/cli"
"github.com/spf13/cobra"
)

func cliMain() {
cli.Run()
var (
output string
)

func newCommand() *cobra.Command {
newCommand := &cobra.Command{
Use: "new",
}
oversize marked this conversation as resolved.
Show resolved Hide resolved

newCommand.AddCommand(
newWalletCommand(),
)
return newCommand
}

func newWalletCommand() *cobra.Command {
newWalletCommand := cobra.Command{
Use: "wallet",
Short: "Creates a new wallet",
Run: func(cmd *cobra.Command, args []string) {
cli.Run(output)
},
}

newWalletCommand.PersistentFlags().StringVar(&output, "output", "", "")

return &newWalletCommand
}
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ go 1.20
require (
github.com/fivebinaries/go-cardano-serialization v0.0.0-20220907134105-ec9b85086588
github.com/fxamacker/cbor/v2 v2.6.0
github.com/gin-contrib/zap v1.1.3
github.com/gin-gonic/gin v1.10.0
github.com/kelseyhightower/envconfig v1.4.0
github.com/penglongli/gin-metrics v0.1.10
github.com/spf13/cobra v1.8.0
github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.0
github.com/swaggo/swag v1.16.3
github.com/tyler-smith/go-bip39 v1.1.0
go.uber.org/zap v1.27.0
golang.org/x/sync v0.7.0
)

Expand All @@ -40,6 +39,7 @@ require (
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
Expand All @@ -55,10 +55,10 @@ require (
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/x448/float16 v0.8.4 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
Expand Down
15 changes: 8 additions & 7 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJ
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand All @@ -97,8 +98,6 @@ github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcP
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-contrib/zap v1.1.3 h1:9e/U9fYd4/OBfmSEBs5hHZq114uACn7bpuzvCkcJySA=
github.com/gin-contrib/zap v1.1.3/go.mod h1:+BD/6NYZKJyUpqVoJEvgeq9GLz8pINEQvak9LHNOTSE=
github.com/gin-gonic/gin v1.7.4/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
Expand Down Expand Up @@ -193,6 +192,8 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
Expand Down Expand Up @@ -283,9 +284,14 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU=
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
Expand Down Expand Up @@ -327,11 +333,6 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
Expand Down
28 changes: 12 additions & 16 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@
import (
"fmt"
"net/http"
"time"

ginzap "github.com/gin-contrib/zap"
"log/slog"

Check failure on line 21 in internal/api/api.go

View workflow job for this annotation

GitHub Actions / go-test (1.20.x, ubuntu-latest)

package log/slog is not in GOROOT (/opt/hostedtoolcache/go/1.20.14/x64/src/log/slog)

Check failure on line 21 in internal/api/api.go

View workflow job for this annotation

GitHub Actions / go-test (1.20.x, macos-latest)

package log/slog is not in GOROOT (/Users/runner/hostedtoolcache/go/1.20.14/arm64/src/log/slog)
oversize marked this conversation as resolved.
Show resolved Hide resolved

"github.com/gin-gonic/gin"
"github.com/penglongli/gin-metrics/ginmetrics"
swaggerFiles "github.com/swaggo/files" // swagger embed files
ginSwagger "github.com/swaggo/gin-swagger" // gin-swagger middleware

"github.com/blinklabs-io/bursa"
"github.com/blinklabs-io/bursa/internal/config"
"github.com/blinklabs-io/bursa/internal/logging"

_ "github.com/blinklabs-io/bursa/docs" // docs is generated by Swag CLI
)
Expand Down Expand Up @@ -58,16 +57,14 @@
router := gin.New()
// Catch panics and return a 500
router.Use(gin.Recovery())
// Standard logging
logger := logging.GetLogger()
// Access logging
accessLogger := logging.GetAccessLogger()
router.Use(ginzap.GinzapWithConfig(accessLogger, &ginzap.Config{
TimeFormat: time.RFC3339,
UTC: true,
SkipPaths: []string{},
}))
router.Use(ginzap.RecoveryWithZap(accessLogger, true))
// accessLogger := logging.GetAccessLogger()
//router.Use(ginzap.GinzapWithConfig(accessLogger, &ginzap.Config{
// TimeFormat: time.RFC3339,
// UTC: true,
// SkipPaths: []string{},
//}))
//router.Use(ginzap.RecoveryWithZap(accessLogger, true))
oversize marked this conversation as resolved.
Show resolved Hide resolved

// Create a healthcheck
router.GET("/healthcheck", handleHealthcheck)
Expand Down Expand Up @@ -111,7 +108,7 @@
// Start metrics listener
go func() {
// TODO: return error if we cannot initialize metrics
logger.Infof("starting metrics listener on %s:%d",
slog.Info("starting metrics listener on %s:%d",
cfg.Metrics.ListenAddress,
cfg.Metrics.ListenPort,
)
Expand Down Expand Up @@ -145,11 +142,10 @@
// @Success 200 {object} bursa.Wallet "Ok"
// @Router /api/wallet/create [get]
func handleWalletCreate(c *gin.Context) {
logger := logging.GetLogger()

mnemonic, err := bursa.NewMnemonic()
if err != nil {
logger.Errorf("failed to load mnemonic: %s", err)
slog.Error("failed to load mnemonic: %s", err)
c.JSON(500, fmt.Sprintf("failed to load mnemonic: %s", err))
_ = ginmetrics.GetMonitor().
GetMetric("bursa_wallets_fail_count").
Expand All @@ -159,7 +155,7 @@

w, err := bursa.NewDefaultWallet(mnemonic)
if err != nil {
logger.Errorf("failed to initialize wallet: %s", err)
slog.Error("failed to initialize wallet: %s", err)
c.JSON(500, fmt.Sprintf("failed to initialize wallet: %s", err))
_ = ginmetrics.GetMonitor().
GetMetric("bursa_wallets_fail_count").
Expand Down
Loading
Loading