forked from xxxserxxx/gotop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
68 lines (59 loc) · 1.66 KB
/
registry.go
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
57
58
59
60
61
62
63
64
65
66
67
68
package colorschemes
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/xxxserxxx/lingo"
"github.com/shibukawa/configdir"
)
var registry map[string]Colorscheme
func init() {
if registry == nil {
registry = make(map[string]Colorscheme)
}
}
var tr lingo.Translations
// Set the translation library
func SetTr(tra lingo.Translations) {
tr = tra
}
// FromName loads a Colorscheme by name; confDir is used to search
// directories for a scheme matching the name. The search order
// is the same as for config files.
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)
}
c.Name = name
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(tr.Value("error.colorschemefile", fn, strings.Join(paths, ", ")))
}
dat, err := folder.ReadFile(fn)
if err != nil {
return cs, fmt.Errorf(tr.Value("error.colorschemeload", filepath.Join(folder.Path, fn), err.Error()))
}
err = json.Unmarshal(dat, &cs)
if err != nil {
return cs, fmt.Errorf(tr.Value("error.colorschemeparse", err.Error()))
}
return cs, nil
}