summaryrefslogtreecommitdiffstats
path: root/colorschemes/registry.go
blob: d79271dfc1d0ee010828fc677045ee0b0604bd12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
}