File: cobra.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.8.17-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,332 kB
  • sloc: sh: 61; makefile: 5
file content (37 lines) | stat: -rw-r--r-- 865 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package util

import (
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// LoadFlagsFromAltSources is a WORKAROUND to make cobra count env vars and
// positional arguments when checking required flags.
func LoadFlagsFromAltSources(cmd *cobra.Command, args []string) {
	flags := cmd.Flags()

	if len(args) > 0 {
		_ = flags.Set("url", args[0])

		if len(args) > 1 {
			_ = flags.Set("message", args[1])
		}

		return
	}

	if hasURLInEnvButNotFlag(cmd) {
		_ = flags.Set("url", viper.GetViper().GetString("SHOUTRRR_URL"))

		// If the URL has been set in ENV, default the message to read from stdin.
		if msg, _ := flags.GetString("message"); msg == "" {
			_ = flags.Set("message", "-")
		}
	}
}

func hasURLInEnvButNotFlag(cmd *cobra.Command) bool {
	s, _ := cmd.Flags().GetString("url")

	return s == "" && viper.GetViper().GetString("SHOUTRRR_URL") != ""
}