root.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. logPath, _ := flags.GetString("log-path")
  37. if err := logger.Load(logPath, level); err != nil {
  38. return fmt.Errorf("failed to load logger: %w", err)
  39. }
  40. configPath, _ := flags.GetString("config-path")
  41. cfg, err := config.Load(configPath)
  42. if err != nil {
  43. return fmt.Errorf("failed to load config: %w", err)
  44. }
  45. token, _ := flags.GetString("token")
  46. if token == "" {
  47. token, err = keyring.Get(consts.Name, "token")
  48. if err != nil {
  49. slog.Info("failed to retrieve token from keyring", "err", err)
  50. }
  51. }
  52. tview.Styles.PrimitiveBackgroundColor = tcell.GetColor(cfg.Theme.BackgroundColor)
  53. app = newApplication(cfg)
  54. return app.run(token)
  55. },
  56. }
  57. Execute = rootCmd.Execute
  58. )
  59. func init() {
  60. flags := rootCmd.Flags()
  61. flags.StringP("token", "t", "", "authentication token")
  62. flags.String("config-path", config.DefaultPath(), "path of the configuration file")
  63. flags.String("log-path", logger.DefaultPath(), "path of the log file")
  64. flags.String("log-level", "info", "log level")
  65. }