-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_config.go
300 lines (247 loc) · 6.63 KB
/
data_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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package data
import (
// "code.google.com/p/gcfg"
"fmt"
"github.com/gonuts/flag"
"github.com/jbenet/commander"
"io"
"os"
"os/exec"
"os/user"
"strings"
)
// WARNING: the config format will be ini eventually. Go parsers
// don't currently allow writing (modifying) of files.
// Thus, for now, using yaml. Expect this to change.
var cmd_data_config = &commander.Command{
UsageLine: "config <command> <key> [<value>]",
Short: "Manage data configuration.",
Long: `data config - Manage data configuration.
Usage:
data config <key> [<value>]
Get or set configuration option values.
If <value> argument is not provided, print <key> value, and exit.
If <value> argument is provided, set <key> to <value>, and exit.
# sets foo.bar = buzz
> data config foo.bar baz
# gets foo.bar
> data config foo.bar
baz
Config options are stored in the user's configuration file (~/.dataconfig).
This file is formatted in YAML, and uses the goyaml parser. (In the future,
it may be formatted like .gitconfig (INI style), using the gcfg parser.)
`,
Run: configCmd,
Flag: *flag.NewFlagSet("data-config", flag.ExitOnError),
}
func init() {
cmd_data_config.Flag.Bool("show", false, "show config file")
cmd_data_config.Flag.Bool("edit", false, "edit config file in $EDITOR")
}
func configCmd(c *commander.Command, args []string) error {
if c.Flag.Lookup("show").Value.Get().(bool) {
return printConfig(&Config)
}
if c.Flag.Lookup("edit").Value.Get().(bool) {
return configEditor()
}
if len(args) == 0 {
return fmt.Errorf("%s: requires <key> argument.", c.Name())
}
if len(args) == 1 {
value := ConfigGet(args[0])
if value == nil {
return fmt.Errorf("") // empty string prints out nothing.
}
m, err := Marshal(value)
if err != nil {
return err
}
io.Copy(os.Stdout, m)
return nil
}
return ConfigSet(args[0], args[1])
}
func printConfig(c *ConfigFormat) error {
f, _ := NewConfigfile("")
f.Config = *c
return f.Write(os.Stdout)
}
func configEditor() error {
ed := os.Getenv("EDITOR")
if len(ed) < 1 {
pErr("No $EDITOR defined. Defaulting to `nano`.")
ed = "nano"
}
ed, args := execCmdArgs(ed, []string{globalConfigFile})
cmd := exec.Command(ed, args...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
return cmd.Run()
}
func ConfigGetString(key string, default_ string) string {
val := ConfigGet(key)
if val == nil {
return default_
}
return fmt.Sprintf("%s", val)
}
func ConfigGet(key string) interface{} {
// struct -> map for dynamic walking
m := map[interface{}]interface{}{}
err := MarshalUnmarshal(Config, &m)
if err != nil {
pErr("data config: error serializing: %s", err)
return nil
}
var cursor interface{}
var exists bool
cursor = m
for _, part := range strings.Split(key, ".") {
cursor, exists = cursor.(map[interface{}]interface{})[part]
if !exists {
return nil
}
}
return cursor
}
func ConfigSet(key string, value string) error {
// struct -> map for dynamic walking
m := map[interface{}]interface{}{}
if err := MarshalUnmarshal(Config, &m); err != nil {
return fmt.Errorf("error serializing config: %s", err)
}
var cursor interface{}
var exists bool
cursor = m
parts := strings.Split(key, ".")
for n, part := range parts {
mcursor := cursor.(map[interface{}]interface{})
// last part, set here.
if n == (len(parts) - 1) {
mcursor[part] = value
break
}
cursor, exists = mcursor[part]
if !exists { // create map if not here.
mcursor[part] = map[interface{}]interface{}{}
cursor = mcursor[part]
}
}
// write back.
if err := MarshalUnmarshal(&m, Config); err != nil {
return fmt.Errorf("error serializing config: %s", err)
}
return WriteConfigFile(globalConfigFile, &Config)
}
var globalConfigFile = "~/.dataconfig"
// type ConfigFormat struct {
// Index map[string]*struct {
// Url string
// User string
// Token string
// Disabled bool ",omitempty"
// }
// }
type ConfigFormat map[string]interface{}
var Config = ConfigFormat{}
// var DefaultConfigText = `[index "datadex.io:8080"]
// user =
// token =
// `
var DefaultConfigText = `index:
datadex:
url: http://datadex.io
user: ""
token: ""
`
// Load config file on statup
func init() {
// alt config file path
if cf := os.Getenv("DATA_CONFIG"); len(cf) > 0 {
globalConfigFile = cf
pErr("Using config file path: %s\n", globalConfigFile)
}
// expand ~/
usr, err := user.Current()
if err != nil {
panic("error: user context. " + err.Error())
}
dir := usr.HomeDir + "/"
globalConfigFile = strings.Replace(globalConfigFile, "~/", dir, 1)
// install config if doesn't exist
if _, err := os.Stat(globalConfigFile); os.IsNotExist(err) {
err := WriteConfigFileText(globalConfigFile, DefaultConfigText)
if err != nil {
panic("error: failed to write config " + globalConfigFile +
". " + err.Error())
}
pErr("Wrote new config file: %s\n", globalConfigFile)
}
// load config
err = ReadConfigFile(globalConfigFile, &Config)
if err != nil {
panic("error: failed to load config " + globalConfigFile +
". " + err.Error())
}
}
func WriteConfigFileText(filename string, text string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write([]byte(text))
return err
}
func WriteConfigFile(filename string, fmt *ConfigFormat) error {
// return gcfg.WriteFile(fmt, filename)
f, _ := NewConfigfile(filename)
f.Config = *fmt
return f.WriteFile()
}
func ReadConfigFile(filename string, fmt *ConfigFormat) error {
// return gcfg.ReadFileInto(fmt, filename)
f, err := NewConfigfile(filename)
if err != nil {
return err
}
*fmt = f.Config
return nil
}
// for use with YAML-based config
type Configfile struct {
SerializedFile "-"
Config ConfigFormat ""
}
func NewConfigfile(path string) (*Configfile, error) {
f := &Configfile{SerializedFile: SerializedFile{Path: path}}
f.Config = ConfigFormat{}
f.SerializedFile.Format = &f.Config
if len(path) > 0 {
err := f.ReadFile()
if err != nil {
return f, err
}
}
return f, nil
}
// nice helpers
const AnonymousUser = "anonymous"
func configUser() string {
return ConfigGetString(fmt.Sprintf("index.%s.user", mainIndexName), "")
}
func configGetIndex(name string) (map[string]string, error) {
idx_raw := ConfigGet("index." + name)
idx, ok := idx_raw.(map[interface{}]interface{})
if idx_raw == nil || !ok {
return nil, fmt.Errorf("Config error: invalid index.%s", name)
}
sidx := map[string]string{}
for k, v := range idx {
sidx[k.(string)] = fmt.Sprintf("%s", v)
}
return sidx, nil
}
func isNamedUser(user string) bool {
return len(user) > 0 && user != AnonymousUser
}