root.go 1.8 KB

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