app.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Package cmd provides the ntfy CLI application
  2. package cmd
  3. import (
  4. "fmt"
  5. "github.com/urfave/cli/v2"
  6. "github.com/urfave/cli/v2/altsrc"
  7. "heckel.io/ntfy/config"
  8. "heckel.io/ntfy/server"
  9. "log"
  10. "os"
  11. )
  12. // New creates a new CLI application
  13. func New() *cli.App {
  14. flags := []cli.Flag{
  15. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: "/etc/ntfy/config.yml", DefaultText: "/etc/ntfy/config.yml", Usage: "config file"},
  16. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-http", Aliases: []string{"l"}, EnvVars: []string{"NTFY_LISTEN_HTTP"}, Value: config.DefaultListenHTTP, Usage: "ip:port used to as listen address"}),
  17. }
  18. return &cli.App{
  19. Name: "ntfy",
  20. Usage: "Simple pub-sub notification service",
  21. UsageText: "ntfy [OPTION..]",
  22. HideHelp: true,
  23. HideVersion: true,
  24. EnableBashCompletion: true,
  25. UseShortOptionHandling: true,
  26. Reader: os.Stdin,
  27. Writer: os.Stdout,
  28. ErrWriter: os.Stderr,
  29. Action: execRun,
  30. Before: initConfigFileInputSource("config", flags),
  31. Flags: flags,
  32. }
  33. }
  34. func execRun(c *cli.Context) error {
  35. // Read all the options
  36. listenHTTP := c.String("listen-http")
  37. // Run main bot, can be killed by signal
  38. conf := config.New(listenHTTP)
  39. s := server.New(conf)
  40. if err := s.Run(); err != nil {
  41. log.Fatalln(err)
  42. }
  43. log.Printf("Exiting.")
  44. return nil
  45. }
  46. // initConfigFileInputSource is like altsrc.InitInputSourceWithContext and altsrc.NewYamlSourceFromFlagFunc, but checks
  47. // if the config flag is exists and only loads it if it does. If the flag is set and the file exists, it fails.
  48. func initConfigFileInputSource(configFlag string, flags []cli.Flag) cli.BeforeFunc {
  49. return func(context *cli.Context) error {
  50. configFile := context.String(configFlag)
  51. if context.IsSet(configFlag) && !fileExists(configFile) {
  52. return fmt.Errorf("config file %s does not exist", configFile)
  53. } else if !context.IsSet(configFlag) && !fileExists(configFile) {
  54. return nil
  55. }
  56. inputSource, err := altsrc.NewYamlSourceFromFile(configFile)
  57. if err != nil {
  58. return err
  59. }
  60. return altsrc.ApplyInputSourceValues(context, inputSource, flags)
  61. }
  62. }
  63. func fileExists(filename string) bool {
  64. stat, _ := os.Stat(filename)
  65. return stat != nil
  66. }