Use XDG directories, and respect corresponding environment vars
This commit is contained in:
parent
a42dd60a16
commit
e60a990d10
@ -8,6 +8,29 @@ import "strconv"
|
||||
import "image/color"
|
||||
import "path/filepath"
|
||||
|
||||
|
||||
// when making changes to this file, look at
|
||||
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
||||
|
||||
// Error represents an error that can be returned by functions or methods in
|
||||
// this module.
|
||||
type Error int
|
||||
|
||||
const (
|
||||
// ErrorIllegalName is thrown when an application name contains illegal
|
||||
// characters such as a slash.
|
||||
ErrorIllegalName Error = iota
|
||||
)
|
||||
|
||||
func (err Error) Error () (description string) {
|
||||
switch err {
|
||||
case ErrorIllegalName:
|
||||
description = "name contains illegal characters"
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Type represents the data type of a configuration parameter.
|
||||
type Type int
|
||||
|
||||
@ -41,9 +64,15 @@ type Config struct {
|
||||
Parameters map[string] any
|
||||
}
|
||||
|
||||
// Load loads and parses the files /etc/<name>/<name>.conf and
|
||||
// <home>/.config/<name>/<name>.conf.
|
||||
// Load loads and parses the files /etc/xdg/<name>/<name>.conf and
|
||||
// <home>/.config/<name>/<name>.conf, unless the corresponding XDG environment
|
||||
// variables are set - then it uses those.
|
||||
func (config *Config) Load (name string) (err error) {
|
||||
if strings.ContainsAny(name, "/\\|:.%") {
|
||||
err = ErrorIllegalName
|
||||
return
|
||||
}
|
||||
|
||||
if config.LegalParameters == nil {
|
||||
config.LegalParameters = make(map[string] Type)
|
||||
}
|
||||
@ -51,12 +80,28 @@ func (config *Config) Load (name string) (err error) {
|
||||
if config.Parameters == nil {
|
||||
config.Parameters = make(map[string] any)
|
||||
}
|
||||
|
||||
config.loadFile("/etc/" + name + "/" + name + ".conf")
|
||||
|
||||
var homeDirectory string
|
||||
homeDirectory, err = os.UserHomeDir()
|
||||
if err != nil { return }
|
||||
config.loadFile(filepath.Join(homeDirectory, "/.config/" + name + "/" + name + ".conf"))
|
||||
|
||||
configHome := os.Getenv("XDG_CONFIG_HOME")
|
||||
if configHome == "" {
|
||||
configHome = filepath.Join(homeDirectory, "/.config/")
|
||||
}
|
||||
|
||||
configDirsString := os.Getenv("XDG_CONFIG_DIRS")
|
||||
if configDirsString == "" {
|
||||
configDirsString = "/etc/xdg/"
|
||||
}
|
||||
|
||||
configDirs := strings.Split(configDirsString, ":")
|
||||
configDirs = append(configDirs, configHome)
|
||||
|
||||
for _, directory := range configDirs {
|
||||
config.loadFile(filepath.Join(directory, name, name + ".conf"))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user