Debian Codegraph @

internal/util/cobra.go

raw
1 // Package util provides utility functions for the shoutrrr CLI application.
2 package util
3
4 import (
5 "fmt"
6
7 "github.com/spf13/cobra"
8 "github.com/spf13/viper"
9 )
10
11 // LoadFlagsFromAltSources is a workaround to make cobra count env vars and
12 // positional arguments when checking required flags.
13 //
14 // It resolves the url and message flags from positional arguments (if provided)
15 // or from the SHOUTRRR_URL environment variable. When the URL is sourced from
16 // the environment, the message defaults to stdin ("-") unless already set.
17 //
18 // Parameters:
19 // - cmd: the cobra.Command whose flags will be populated.
20 // - args: positional arguments passed to the command.
21 //
22 // Returns:
23 // - error: if any flag operation fails; otherwise nil.
24 func LoadFlagsFromAltSources(cmd *cobra.Command, args []string) error {
25 flags := cmd.Flags()
26
27 if len(args) > 0 {
28 if err := flags.Set("url", args[0]); err != nil {
29 return fmt.Errorf("setting url flag from positional arg: %w", err)
30 }
31
32 if len(args) > 1 {
33 if err := flags.Set("message", args[1]); err != nil {
34 return fmt.Errorf("setting message flag from positional arg: %w", err)
35 }
36 }
37
38 return nil
39 }
40
41 hasURL, err := hasURLInEnvButNotFlag(cmd)
42 if err != nil {
43 return fmt.Errorf("checking url flag and env: %w", err)
44 }
45
46 if hasURL {
47 if err := flags.Set("url", viper.GetViper().GetString("SHOUTRRR_URL")); err != nil {
48 return fmt.Errorf("setting url flag from env var: %w", err)
49 }
50
51 // Default the message to read from stdin when the URL is sourced from env.
52 msg, err := flags.GetString("message")
53 if err != nil {
54 return fmt.Errorf("getting message flag value: %w", err)
55 }
56
57 if msg == "" {
58 if err := flags.Set("message", "-"); err != nil {
59 return fmt.Errorf("setting message flag to default stdin: %w", err)
60 }
61 }
62 }
63
64 return nil
65 }
66
67 // hasURLInEnvButNotFlag checks whether the SHOUTRRR_URL environment variable is
68 // set while no url flag has been explicitly provided on the command.
69 //
70 // Cobra StringArray flags default to [""] rather than a truly empty slice, so
71 // both cases are treated as "no URL provided via flag".
72 //
73 // Parameters:
74 // - cmd: the cobra.Command to inspect.
75 //
76 // Returns:
77 // - bool: true when the env var is set and the flag is empty.
78 // - error: if the url flag cannot be read.
79 func hasURLInEnvButNotFlag(cmd *cobra.Command) (bool, error) {
80 urls, err := cmd.Flags().GetStringArray("url")
81 if err != nil {
82 return false, fmt.Errorf("getting url flag value: %w", err)
83 }
84
85 // Treat an empty slice or a single-element slice containing "" as "no URL provided".
86 flagEmpty := len(urls) == 0 || (len(urls) == 1 && urls[0] == "")
87
88 return flagEmpty && viper.GetViper().GetString("SHOUTRRR_URL") != "", nil
89 }