root.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/app"
  8. "github.com/ayn2op/discordo/internal/config"
  9. "github.com/ayn2op/discordo/internal/consts"
  10. "github.com/ayn2op/discordo/internal/keyring"
  11. "github.com/ayn2op/discordo/internal/logger"
  12. "github.com/diamondburned/arikawa/v3/utils/ws"
  13. "github.com/spf13/cobra"
  14. )
  15. var (
  16. token string
  17. configPath string
  18. logPath string
  19. logLevel string
  20. rootCmd = &cobra.Command{
  21. Use: consts.Name,
  22. RunE: func(cmd *cobra.Command, args []string) error {
  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. if err := logger.Load(logPath, level); err != nil {
  36. return fmt.Errorf("failed to load logger: %w", err)
  37. }
  38. cfg, err := config.Load(configPath)
  39. if err != nil {
  40. return fmt.Errorf("failed to load config: %w", err)
  41. }
  42. if token == "" {
  43. token = os.Getenv("DISCORDO_TOKEN")
  44. }
  45. if token == "" {
  46. token, err = keyring.GetToken()
  47. if err != nil {
  48. slog.Info("failed to retrieve token from keyring", "err", err)
  49. }
  50. }
  51. return app.New(cfg).Run(token)
  52. },
  53. }
  54. Execute = rootCmd.Execute
  55. )
  56. func init() {
  57. flags := rootCmd.Flags()
  58. flags.StringVar(&token, "token", "", "authentication token (default: $DISCORDO_TOKEN or keyring)")
  59. flags.StringVar(&configPath, "config-path", config.DefaultPath(), "path of the configuration file")
  60. flags.StringVar(&logPath, "log-path", logger.DefaultPath(), "path of the log file")
  61. flags.StringVar(&logLevel, "log-level", "info", "log level")
  62. }