config: add default path, customized configs.

A customised config is an ini file with a [default] section and some
other name sections; a config file is loaded from the default section
with any keys in the named section being added in, overriding keys in
the host. This allows for, e.g. setting different paths based on the
host name or operating system.
This commit is contained in:
2022-02-20 17:40:38 -08:00
parent c7c51568d8
commit b893e99864
6 changed files with 465 additions and 0 deletions

View File

@@ -10,9 +10,12 @@ package config
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"git.sr.ht/~kisom/goutils/config/iniconf"
)
// NB: Rather than define a singleton type, everything is defined at
@@ -67,6 +70,34 @@ func LoadFile(path string) error {
return nil
}
// LoadFileFor scans the ini file at path, loading the default section
// and overriding any keys found under section. If strict is true, the
// named section must exist (i.e. to catch typos in the section name).
func LoadFileFor(path, section string, strict bool) error {
cmap, err := iniconf.ParseFile(path)
if err != nil {
return err
}
for key, value := range cmap[iniconf.DefaultSection] {
vars[key] = value
}
smap, ok := cmap[section]
if !ok {
if strict {
return fmt.Errorf("config: section '%s' wasn't found in the config file", section)
}
return nil
}
for key, value := range smap {
vars[key] = value
}
return nil
}
// Get retrieves a value from either a configuration file or the
// environment. Note that values from a file will override environment
// variables.