root.go 1.9 KB

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