summaryrefslogtreecommitdiffstats
path: root/colorschemes/registry.go
blob: b6263c97aa527a26b2442c1c215573452083f500 (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
50
51
52
53
54
55
56
package colorschemes

import (
	"encoding/json"
	"fmt"
	"path/filepath"
	"strings"

	"github.com/shibukawa/configdir"
)

var registry map[string]Colorscheme

func init() {
	if registry == nil {
		registry = make(map[string]Colorscheme)
	}
}

func FromName(confDir configdir.ConfigDir, c string) (Colorscheme, error) {
	if cs, ok := registry[c]; ok {
		return cs, nil
	}
	cs, err := getCustomColorscheme(confDir, c)
	return cs, err
}

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 configdir.ConfigDir, name string) (Colorscheme, error) {
	var cs Colorscheme
	fn := name + ".json"
	folder := confDir.QueryFolderContainsFile(fn)
	if folder == nil {
		paths := make([]string, 0)
		for _, d := range confDir.QueryFolders(configdir.Existing) {
			paths = append(paths, d.Path)
		}
		return cs, fmt.Errorf("failed to find colorscheme file %s in %s", fn, strings.Join(paths, ", "))
	}
	dat, err := folder.ReadFile(fn)
	if err != nil {
		return cs, fmt.Errorf("failed to read colorscheme file %s: %v", filepath.Join(folder.Path, fn), err)
	}
	err = json.Unmarshal(dat, &cs)
	if err != nil {
		return cs, fmt.Errorf("failed to parse colorscheme file: %v", err)
	}
	return cs, nil
}