xmtop/colorschemes/registry.go
Sean E. Russell 9188b14094 Safety: prevent uninitialized variable use
Record change

Fixes changelog
2020-03-07 08:35:27 -06:00

50 lines
1.0 KiB
Go

package colorschemes
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
)
var registry map[string]Colorscheme
func init() {
if registry == nil {
registry = make(map[string]Colorscheme)
}
}
func FromName(confDir string, c string) (Colorscheme, error) {
cs, ok := registry[c]
if !ok {
cs, err := getCustomColorscheme(confDir, c)
if err != nil {
return cs, err
}
}
return cs, nil
}
func register(name string, c Colorscheme) {
if registry == nil {
registry = make(map[string]Colorscheme)
}
registry[name] = c
}
// getCustomColorscheme tries to read a custom json colorscheme from <configDir>/<name>.json
func getCustomColorscheme(confDir string, name string) (Colorscheme, error) {
var cs Colorscheme
filePath := filepath.Join(confDir, name+".json")
dat, err := ioutil.ReadFile(filePath)
if err != nil {
return cs, fmt.Errorf("failed to read colorscheme file: %v", err)
}
err = json.Unmarshal(dat, &cs)
if err != nil {
return cs, fmt.Errorf("failed to parse colorscheme file: %v", err)
}
return cs, nil
}