root.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Package cmd defines the command-line interface commands
  2. package cmd
  3. import (
  4. "fmt"
  5. "log/slog"
  6. "github.com/ayn2op/discordo/internal/config"
  7. "github.com/ayn2op/discordo/internal/consts"
  8. "github.com/ayn2op/discordo/internal/logger"
  9. "github.com/ayn2op/tview"
  10. "github.com/diamondburned/arikawa/v3/utils/ws"
  11. "github.com/diamondburned/ningen/v3"
  12. "github.com/gdamore/tcell/v2"
  13. "github.com/spf13/cobra"
  14. "github.com/zalando/go-keyring"
  15. )
  16. var (
  17. discordState *ningen.State
  18. app *application
  19. rootCmd = &cobra.Command{
  20. Use: consts.Name,
  21. RunE: func(cmd *cobra.Command, _ []string) error {
  22. flags := cmd.Flags()
  23. logLevel, _ := flags.GetString("log-level")
  24. var level slog.Level
  25. switch logLevel {
  26. case "debug":
  27. ws.EnableRawEvents = true
  28. level = slog.LevelDebug
  29. case "info":
  30. level = slog.LevelInfo
  31. case "warn":
  32. level = slog.LevelWarn
  33. case "error":
  34. level = slog.LevelError
  35. }
  36. logFormat, _ := flags.GetString("log-format")
  37. var format logger.Format
  38. switch logFormat {
  39. case "text":
  40. format = logger.FormatText
  41. case "json":
  42. format = logger.FormatJson
  43. }
  44. if err := logger.Load(format, level); err != nil {
  45. return fmt.Errorf("failed to load logger: %w", err)
  46. }
  47. configPath, _ := flags.GetString("config")
  48. cfg, err := config.Load(configPath)
  49. if err != nil {
  50. return fmt.Errorf("failed to load config: %w", err)
  51. }
  52. tview.Styles.PrimitiveBackgroundColor = tcell.GetColor(cfg.Theme.BackgroundColor)
  53. token, _ := flags.GetString("token")
  54. if token == "" {
  55. token, err = keyring.Get(consts.Name, "token")
  56. if err != nil {
  57. slog.Info("failed to retrieve token from keyring", "err", err)
  58. }
  59. }
  60. app = newApplication(cfg)
  61. return app.run(token)
  62. },
  63. }
  64. Execute = rootCmd.Execute
  65. )
  66. func init() {
  67. flags := rootCmd.Flags()
  68. flags.StringP("token", "t", "", "authentication token")
  69. flags.StringP("config", "c", config.DefaultPath(), "path of the configuration file")
  70. flags.String("log-level", "info", "log level")
  71. flags.String("log-format", "text", "log format")
  72. }