Debian Codegraph @

cmd/config_loader.go

raw
1 package cmd
2
3 import (
4 "fmt"
5 "github.com/urfave/cli/v2"
6 "github.com/urfave/cli/v2/altsrc"
7 "gopkg.in/yaml.v2"
8 "heckel.io/ntfy/v2/util"
9 "os"
10 )
11
12 // initConfigFileInputSourceFunc is like altsrc.InitInputSourceWithContext and altsrc.NewYamlSourceFromFlagFunc, but checks
13 // if the config flag is exists and only loads it if it does. If the flag is set and the file exists, it fails.
14 func initConfigFileInputSourceFunc(configFlag string, flags []cli.Flag, next cli.BeforeFunc) cli.BeforeFunc {
15 return func(context *cli.Context) error {
16 configFile := context.String(configFlag)
17 if context.IsSet(configFlag) && !util.FileExists(configFile) {
18 return fmt.Errorf("config file %s does not exist", configFile)
19 } else if !context.IsSet(configFlag) && !util.FileExists(configFile) {
20 return nil
21 }
22 inputSource, err := newYamlSourceFromFile(configFile, flags)
23 if err != nil {
24 return err
25 }
26 if err := altsrc.ApplyInputSourceValues(context, inputSource, flags); err != nil {
27 return err
28 }
29 if next != nil {
30 if err := next(context); err != nil {
31 return err
32 }
33 }
34 return nil
35 }
36 }
37
38 // newYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath.
39 //
40 // This function also maps aliases, so a .yml file can contain short options, or options with underscores
41 // instead of dashes. See https://github.com/binwiederhier/ntfy/issues/255.
42 func newYamlSourceFromFile(file string, flags []cli.Flag) (altsrc.InputSourceContext, error) {
43 var rawConfig map[any]any
44 b, err := os.ReadFile(file)
45 if err != nil {
46 return nil, err
47 }
48 if err := yaml.Unmarshal(b, &rawConfig); err != nil {
49 return nil, err
50 }
51 for _, f := range flags {
52 flagName := f.Names()[0]
53 for _, flagAlias := range f.Names()[1:] {
54 if _, ok := rawConfig[flagAlias]; ok {
55 rawConfig[flagName] = rawConfig[flagAlias]
56 }
57 }
58 }
59 return altsrc.NewMapInputSource(file, rawConfig), nil
60 }