root.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/spf13/cobra"
  13. "github.com/zalando/go-keyring"
  14. )
  15. var (
  16. discordState *ningen.State
  17. app *application
  18. rootCmd = &cobra.Command{
  19. Use: consts.Name,
  20. RunE: func(cmd *cobra.Command, _ []string) error {
  21. flags := cmd.Flags()
  22. logLevel, _ := flags.GetString("log-level")
  23. var level slog.Level
  24. switch logLevel {
  25. case "debug":
  26. ws.EnableRawEvents = true
  27. level = slog.LevelDebug
  28. case "info":
  29. level = slog.LevelInfo
  30. case "warn":
  31. level = slog.LevelWarn
  32. case "error":
  33. level = slog.LevelError
  34. }
  35. logPath, _ := flags.GetString("log-path")
  36. if err := logger.Load(logPath, level); err != nil {
  37. return fmt.Errorf("failed to load logger: %w", err)
  38. }
  39. configPath, _ := flags.GetString("config-path")
  40. cfg, err := config.Load(configPath)
  41. if err != nil {
  42. return fmt.Errorf("failed to load config: %w", err)
  43. }
  44. token, _ := flags.GetString("token")
  45. if token == "" {
  46. token, err = keyring.Get(consts.Name, "token")
  47. if err != nil {
  48. slog.Info("failed to retrieve token from keyring", "err", err)
  49. }
  50. }
  51. tview.Styles = tview.Theme{}
  52. app = newApplication(cfg)
  53. return app.run(token)
  54. },
  55. }
  56. Execute = rootCmd.Execute
  57. )
  58. func init() {
  59. flags := rootCmd.Flags()
  60. flags.StringP("token", "t", "", "authentication token")
  61. flags.String("config-path", config.DefaultPath(), "path of the configuration file")
  62. flags.String("log-path", logger.DefaultPath(), "path of the log file")
  63. flags.String("log-level", "info", "log level")
  64. }