This repository has been archived by the owner on Sep 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
124 lines (100 loc) · 2.46 KB
/
config.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package blox
import (
"errors"
"fmt"
"io/ioutil"
"cuelang.org/go/cue"
"github.com/pterm/pterm"
)
type Config struct {
runtime *Runtime
}
// New setup a new config type with
// base as the defaults
func NewConfig(base string) (*Config, error) {
r, err := NewRuntimeWithBase(base)
if err != nil {
return nil, err
}
config := &Config{
runtime: r,
}
return config, nil
}
// LoadConfig opens the configuration file
// specified in `path` and validates it against
// the configuration provided in when the `Engine`
// was initialized with `New()`
func (r *Config) LoadConfig(path string) error {
pterm.Debug.Printf("\t\tLoading config: %s\n", path)
cueConfig, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return r.LoadConfigString(string(cueConfig))
}
func (r *Config) LoadConfigString(cueConfig string) error {
cueValue := r.runtime.CueContext.CompileString(cueConfig)
if cueValue.Err() != nil {
return cueValue.Err()
}
r.runtime.Database = r.runtime.Database.Unify(cueValue)
if err := r.runtime.Database.Validate(); err != nil {
return err
}
return nil
}
func (r *Config) GetString(key string) (string, error) {
keyValue := r.runtime.Database.LookupPath(cue.ParsePath(key))
if keyValue.Exists() {
return keyValue.String()
}
return "", fmt.Errorf("couldn't find key '%s'", key)
}
func (r *Config) GetBool(key string) (bool, error) {
keyValue := r.runtime.Database.LookupPath(cue.ParsePath(key))
if keyValue.Exists() {
return keyValue.Bool()
}
return false, fmt.Errorf("couldn't find key '%s'", key)
}
func (r *Config) GetList(key string) (cue.Value, error) {
keyValue := r.runtime.Database.LookupPath(cue.ParsePath(key))
if keyValue.Exists() {
_, err := keyValue.List()
if err != nil {
return cue.Value{}, err
}
return keyValue, nil
}
return cue.Value{}, errors.New("not found")
}
func (r *Config) GetStringOr(key string, def string) string {
cueValue, err := r.GetString(key)
if err != nil {
return def
}
return cueValue
}
const BaseConfig = `{
#Remote: {
name: string
version: string
repository: string
}
#Plugin: {
name: string
executable: string
}
build_dir: string | *"_build"
data_dir: string | *"data"
schemata_dir: string | *"schemata"
static_dir: string | *"static"
template_dir: string | *"templates"
output_cue: bool | *false
output_recordsets: bool | *false
remotes: [ ...#Remote ]
prebuild: [...#Plugin]
postbuild: [...#Plugin]
}`
const DefaultConfigName = "blox.cue"