From af89b2652be1d1975f3dccc6dcd3264f9747c03a Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Thu, 26 Nov 2020 09:02:43 +0100 Subject: [PATCH] Add config utils This commit introduces utility functions for parsing and validating CLI flags and YAML configuration files. --- pkg/config/config.go | 71 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 pkg/config/config.go diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 00000000..977e6bf0 --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,71 @@ +package config + +import ( + "fmt" + "github.com/jessevdk/go-flags" + "gopkg.in/yaml.v3" + "os" +) + +// Config defines Icinga DB config. +type Config struct { + Database *Database `yaml:"database"` + Redis *Redis `yaml:"redis"` +} + +// Flags defines CLI flags. +type Flags struct { + // Config is the path to the config file + Config string `short:"c" long:"config" description:"path to config file" required:"true" default:"./config.yml"` + // Datadir is the location of the data directory + Datadir string `long:"datadir" description:"path to the data directory" required:"true" default:"./"` +} + +// FromYAMLFile returns a new Config value created from the given YAML config file. +func FromYAMLFile(name string) (*Config, error) { + f, err := os.Open(name) + if err != nil { + return nil, err + } + defer f.Close() + + c := &Config{} + d := yaml.NewDecoder(f) + + if err := d.Decode(&c); err != nil { + return nil, err + } + + return c, nil +} + +// ValidateFile checks whether the given file name is a readable file. +func ValidateFile(name string) error { + f, err := os.Stat(name) + if err != nil { + return err + } + + if f.IsDir() { + return fmt.Errorf("'%s' is a directory", name) + } + + return nil +} + +// ParseFlags parses CLI flags and +// returns a Flags value created from them. +func ParseFlags() (*Flags, error) { + f := &Flags{} + parser := flags.NewParser(f, flags.Default) + + if _, err := parser.Parse(); err != nil { + return nil, err + } + + if err := ValidateFile(f.Config); err != nil { + return nil, err + } + + return f, nil +}