~pkal/dirconf

dirconf/dirconf.go -rw-r--r-- 7.1 KiB
009b06c4 — Philip K added reference to my article on dirconf 2 years ago
                                                                                
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package dirconf

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/user"
	"path/filepath"
	"strconv"
	"strings"
)

const schemaFile = ".schema"

var (
	// ErrWrongType is returned when the content of a value cannot be
	// cast to the requested type
	ErrWrongType = errors.New("wrong type")

	// ErrNoValueFound is returned when a value MUST have a value but no
	// such value could be found
	ErrNoValueFound = errors.New("a value was not found")
)

// Option is any value that
type Option interface {
	Set(c *Conf, file string, r io.Reader) error
}

// PathOption is a Option that can offer a relative file that it's value
// would be found in
type PathOption interface {
	Option
	Name() string
	Path() []string
}

// Conf is a list of Options, each which will be processed when parsed
type Conf []Option

func (c *Conf) writeSchema(dir string) error {
	file, err := os.OpenFile(filepath.Join(dir, schemaFile),
		os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	for _, opt := range *c {
		po, ok := opt.(PathOption)
		if !ok {
			continue
		}
		rfile := filepath.Join(po.Path()...)
		_, err := fmt.Fprintf(file, "%s\t%s\n", po.Name(), rfile)
		if err != nil {
			return err
		}
	}

	return nil
}

func (c *Conf) Parse() error {
	name := filepath.Base(os.Args[0])
	dir := os.Getenv("XDG_CONFIG_HOME")
	if dir == "" {
		me, err := user.Current()
		if err != nil {
			return err
		}
		dir = filepath.Join(me.HomeDir, ".config")
	}

	return c.ParseIn(filepath.Join(dir, name))
}

func (c *Conf) ParseIn(dir string) error {
	err := os.MkdirAll(dir, 0755)
	if err != nil {
		return err
	}

	err = c.writeSchema(dir)
	if err != nil {
		return err
	}

	for _, opt := range *c {
		po, ok := opt.(PathOption)
		if ok {
			fpath := filepath.Join(append([]string{dir}, po.Path()...)...)
			file, err := os.Open(fpath)
			if err != nil {
				opt.Set(c, fpath, nil)
			} else {
				opt.Set(c, fpath, file)
				file.Close()
			}
		} else {
			opt.Set(c, "", nil)
		}
	}

	return nil
}

////////////////
// INT OPTION //
////////////////

// Int is an option for a int
type Int struct {
	Ptr     *int
	Default int
	Must    bool
	OnSet   func(int)
	Key     string
}

// Name returns the name of the option type
func (o *Int) Name() string { return "int" }

// Path returns the relative file of this option
func (o *Int) Path() []string { return strings.Split(o.Key, "/") }

// Set is called when the value of a Int is processed
func (o *Int) Set(c *Conf, file string, r io.Reader) error {
	var val int
	if r == nil {
		if o.Must {
			return ErrNoValueFound
		}
		val = o.Default
	} else {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}

		i, err := strconv.ParseInt(string(data), 10, 0)
		if err != nil {
			return ErrWrongType
		}

		val = int(i)
	}
	if o.Ptr != nil {
		*o.Ptr = val
	}
	if o.OnSet != nil {
		o.OnSet(val)
	}
	return nil
}

//////////////////
// FLOAT OPTION //
//////////////////

// Float is an option for a int
type Float struct {
	Ptr     *float64
	Default float64
	Must    bool
	OnSet   func(float64)
	Key     string
}

// Name returns the name of the option type
func (o *Float) Name() string { return "float" }

// Path returns the relative file of this option
func (o *Float) Path() []string { return strings.Split(o.Key, "/") }

// Set is called when the value of a Int is processed
func (o *Float) Set(c *Conf, file string, r io.Reader) error {
	var val float64
	if r == nil {
		if o.Must {
			return ErrNoValueFound
		}
		val = o.Default
	} else {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}

		val, err = strconv.ParseFloat(string(data), 64)
		if err != nil {
			return ErrWrongType
		}
	}
	if o.Ptr != nil {
		*o.Ptr = val
	}
	if o.OnSet != nil {
		o.OnSet(val)
	}
	return nil
}

///////////////////
// STRING OPTION //
///////////////////

// String is an option for a string
type String struct {
	Ptr     *string
	Default string
	Must    bool
	OnSet   func(string)
	Key     string
}

// Name returns the name of the option type
func (o *String) Name() string { return "string" }

// Path returns the relative file of this option
func (o *String) Path() []string { return strings.Split(o.Key, "/") }

// Set is called when the value of a Int is processed
func (o *String) Set(c *Conf, file string, r io.Reader) error {
	var val string
	if r == nil {
		if o.Must {
			return ErrNoValueFound
		}
		val = o.Default
	} else {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}
		val = string(data)
	}
	if o.Ptr != nil {
		*o.Ptr = val
	}
	if o.OnSet != nil {
		o.OnSet(val)
	}
	return nil
}

/////////////////////////////
// LIST (of string) OPTION //
/////////////////////////////

// List is an option for a string
type List struct {
	Ptr     *[]string
	Default []string
	Must    bool
	OnSet   func([]string)
	Key     string
}

// Name returns the name of the option type
func (o *List) Name() string { return "list" }

// Path returns the relative file of this option
func (o *List) Path() []string { return strings.Split(o.Key, "/") }

// Set is called when the value of a Int is processed
func (o *List) Set(c *Conf, file string, r io.Reader) error {
	var val []string
	if r == nil {
		if o.Must {
			return ErrNoValueFound
		}
		val = o.Default
	} else {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}

		list := bytes.Split(data, []byte("\n"))
		val = make([]string, len(list))
		for i, b := range list {
			val[i] = string(b)
		}
	}
	if o.Ptr != nil {
		*o.Ptr = val
	}
	if o.OnSet != nil {
		o.OnSet(val)
	}
	return nil
}

/////////////////
// BOOL OPTION //
/////////////////

// Bool is an option for a bool
type Bool struct {
	Ptr   *bool
	OnSet func(bool)
	Key   string
}

// Name returns the name of the option type
func (o *Bool) Name() string { return "boolean" }

// Path returns the relative file of this option
func (o *Bool) Path() []string { return strings.Split(o.Key, "/") }

// Set is called when the value of a Int is processed
func (o *Bool) Set(c *Conf, file string, r io.Reader) error {
	if o.Ptr != nil {
		*o.Ptr = r == nil
	}
	if o.OnSet != nil {
		o.OnSet(r == nil)
	}
	return nil
}

////////////////////
// GENERIC OPTION //
////////////////////

// Func is an option for a generic option
type Func struct {
	Func func(r io.Reader) error
	Key  string
}

// Name returns the name of the option type
func (f *Func) Name() string { return "file" }

// Path returns the relative file of this option
func (f *Func) Path() []string { return strings.Split(f.Key, "/") }

// Set is called when the value of a Int is processed
func (f *Func) Set(c *Conf, file string, r io.Reader) error {
	return f.Func(r)
}

/////////////////
// PATH OPTION //
/////////////////

// Path is an option for a to get the path
type Path struct {
	Ptr   *string
	OnSet func(string)
	Key   string
}

// Path returns the relative file of this option
func (o *Path) Path() []string { return strings.Split(o.Key, "/") }

// Set is called when the value of a Int is processed
func (o *Path) Set(c *Conf, file string, r io.Reader) error {
	path := append([]string{file}, strings.Split(o.Key, "/")...)
	val := filepath.Join(path...)
	if o.Ptr != nil {
		*o.Ptr = val
	}
	if o.OnSet != nil {
		o.OnSet(val)
	}
	return nil

}