-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.go
More file actions
422 lines (360 loc) · 9.96 KB
/
env.go
File metadata and controls
422 lines (360 loc) · 9.96 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package env
import (
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
)
// These var should be set externally by the build command
var (
Version, Build string
Description string
)
// Path type returned by NewENV and Configure
type Path struct {
Etc, Srv, Var, Tmp string
}
// NewEnv that sets up the basic envrionment paths and
// calls the Parser to process the struct tag fields and
// populates any interfaces that are provided
//
// tags
// env:"alias,order,require,environ,hidden"
// help:"description"
// default:"value" (bool, string, int)
//
// Action string `env:"A,require" default:"server" help:"action [server|client]"`
func NewEnv(cfg ...interface{}) (path *Path) {
return Configure(cfg...)
}
// Options for env.Configure
//
// Silent: log configuration output
// NoHelp: silences the help output
// SetENV: set KEY=VALUE in environemnt
type Options struct {
Silent bool // silence log configuration output
NoHelp bool // silence help output
SetENV bool // set KEY=VALUE in environment
NoExit bool // return nil instead of os.Exit(0) for version,help
}
// Configure sets up the basic environment and returns environment paths;
// pass Options as the first item to set or specify custom configuration
// options to silence log and help output and env.Options.M map populates,
// struct initially, overloaded by environment vars, overloaded by default
// tag, that is then overloaded by command line swithches, in this order
func Configure(cfg ...interface{}) (path *Path) {
var opt Options
if len(cfg) > 0 {
switch c := cfg[0].(type) {
case *Options:
opt = *c
cfg = cfg[1:]
case Options: // bonehead
opt = c
cfg = cfg[1:]
}
}
var name string
switch runtime.GOOS {
case "linux": // production
path = &Path{
Etc: "/etc",
Srv: "/srv",
Var: "/var",
Tmp: "/tmp",
}
name = filepath.Base(os.Args[0])
// this can be overwritten in production environments
// using the build in commandline log:on functionality
log.SetFlags(0) // Ldate=1 Ltime=2
default: // development
path = &Path{
Etc: "_dev/etc",
Srv: "_dev/srv",
Var: "_dev/var",
Tmp: "_dev/tmp",
}
name = "development"
}
if len(os.Args) > 1 {
var n = 18
if len(name) > n {
n = len(name)
}
if len(Version)+10 > n {
n = len(Version) + 10
}
if len(Build)+10 > n {
n = len(Build) + 10
}
switch strings.TrimLeft(os.Args[1], "-") {
case "version":
fmt.Printf("\n %-s\n%s\n version %s\n build %s\n\n",
name, strings.Repeat("-", n+2), Version, Build)
if opt.NoExit {
return nil
}
os.Exit(0)
case "help":
fmt.Printf("\n %-s\n%s\n version %s\n build %s\n\n",
name, strings.Repeat("-", n+2), Version, Build)
if len(Description) > 0 {
fmt.Printf("%s\n\n", Description)
}
if !opt.NoHelp && len(cfg) > 0 {
for i := range cfg {
var tag string
var ok bool
v := reflect.Indirect(reflect.ValueOf(cfg[i]))
for j := 0; j < v.NumField(); j++ {
// name field
tag, ok = v.Type().Field(j).Tag.Lookup("name")
if !ok {
tag = strings.ToLower(v.Type().Field(j).Name)
}
if !v.Field(j).CanSet() || len(tag) == 0 {
continue // unexported
}
var env struct{ Order, Require, Environ, Hidden, Alias string }
if opts, ok := v.Type().Field(j).Tag.Lookup("env"); ok {
if opts == "-" {
continue
}
for _, v := range strings.Split(opts, ",") {
switch v {
case "order":
env.Order = "o"
case "require":
env.Require = "r"
case "environ":
env.Environ = "e"
case "hidden":
env.Hidden = "*"
default:
env.Alias = v
}
}
}
// fmt.Printf(" %-15s", tag)
fmt.Printf(" %-15s %-5s [%-1s%-1s%-1s%-1s] ",
tag, env.Alias, env.Order, env.Require, env.Environ, env.Hidden)
// default field
tag, _ = v.Type().Field(j).Tag.Lookup("default")
fmt.Printf("default:%-10s ", tag)
// help field
tag, _ = v.Type().Field(j).Tag.Lookup("help")
fmt.Println(tag)
}
}
}
fmt.Println()
if opt.NoExit {
return nil
}
os.Exit(0)
}
}
if len(cfg) > 0 {
opt.parse(cfg...)
}
if !opt.Silent {
usr, _ := user.Current()
log.Printf("|%s|", strings.Repeat("-", 40))
log.Printf("| %s %s event log |", strings.ToUpper(filepath.Base(os.Args[0])), strings.Repeat(":", 27-len(filepath.Base(os.Args[0]))))
log.Printf("|-----//o%s|", strings.Repeat("-", 32))
log.Printf("%s%s version", strings.Repeat(" ", 31-len(Version)), Version)
log.Printf("%s%s build", strings.Repeat(" ", 31-len(Build)), Build)
log.Printf(" %s%spid %d", usr.Username, strings.Repeat(" ", 27-len(usr.Username)), os.Getpid())
log.Printf("|-----//o%s|", strings.Repeat("-", 32))
var tag string
var ok bool
for j := 0; j < len(cfg); j++ {
v := reflect.Indirect(reflect.ValueOf(cfg[j]))
for i := 0; i < v.NumField(); i++ {
if tag, ok = v.Type().Field(i).Tag.Lookup("name"); !ok {
tag = strings.ToLower(v.Type().Field(i).Name)
}
if !v.Field(i).CanSet() || len(tag) == 0 {
continue // unexported
}
if opts, ok := v.Type().Field(i).Tag.Lookup("env"); ok {
if opts == "-" {
continue
}
if strings.Contains(opts, "hidden") {
log.Printf(" %-15s| <hidden>", strings.ToLower(v.Type().Field(i).Name))
continue
}
}
log.Printf(" %-15s| %v", tag, v.Field(i))
}
log.Printf("|%s|", strings.Repeat("-", 40))
}
}
return
}
// parse will set the speficied cfg struct field value according to the tag:env and
// tag:default provided in the struct, and will overload in the following order:
//
// tag:default, conf k:v sets, os.Args, os.Environ
//
// final values in the key:value os.Environment table.
//
// env: alias,require,order,environ field flags
// supports: string, bool, int/64, uint/64 types
func (p *Options) parse(cfg ...interface{}) {
// overlaoding order
// tag:default, conf, os.Args, ENV=
var m = make(map[string]string)
// processes os.Args and build/overload a map[string]string; support for single
// reference switches -a aa -b
for i := 0; i < len(os.Args); i++ {
if strings.HasPrefix(os.Args[i], "-") {
key := strings.TrimLeft(os.Args[i], "-")
switch {
case strings.Contains(key, "="):
s := strings.SplitN(key, "=", 2)
m[s[0]] += s[1]
case strings.Contains(key, ":"):
s := strings.SplitN(key, ":", 2)
m[s[0]] += s[1]
default:
i++
if i < len(os.Args) {
if !strings.HasPrefix(os.Args[i], "-") {
m[key] = os.Args[i]
} else {
i--
}
}
}
}
}
// command line log timestamp controller
// to turn on/off the log timestamp headers
switch m["log"] {
case "on", "yes", "true":
log.SetFlags(log.Ldate | log.Ltime)
delete(m, "log")
case "off", "no", "false":
log.SetFlags(0)
delete(m, "log")
}
// process interfaces
for i := range cfg {
var order = 1
v := reflect.Indirect(reflect.ValueOf(cfg[i]))
if v.Type().Kind() != reflect.Struct {
fmt.Fprintf(os.Stderr, "%s: %s interface misconfigured",
filepath.Base(os.Args[0]), reflect.TypeOf(cfg[i]).Elem().Name())
os.Exit(1)
}
// process fields
for j := 0; j < v.NumField(); j++ {
// get field name
name := strings.ToLower(v.Type().Field(j).Name)
if !v.Field(j).CanSet() || len(name) == 0 {
continue
}
var value string
var status bool
var env struct {
Order, Require, Environ bool
Alias string
}
// process tag:env
if tag, ok := v.Type().Field(j).Tag.Lookup("env"); ok {
if tag == "-" {
continue // ignore
}
for _, v := range strings.Split(tag, ",") {
switch v {
case "order":
env.Order = true
case "require":
env.Require = true
case "environ":
env.Environ = true
// case "hidden":
default:
env.Alias = v
}
}
}
// apply tag:default values; when defined
if val, ok := v.Type().Field(j).Tag.Lookup("default"); ok {
value, status = p.setField(v.Field(j), val)
}
// overload with conf/args values; when present
if val, ok := m[name]; ok {
value, status = p.setField(v.Field(j), val)
}
if val, ok := m[env.Alias]; ok {
value, status = p.setField(v.Field(j), val)
}
// overload with os.Environment table values; when present
if val, ok := os.LookupEnv(strings.ToUpper(name)); ok {
value, status = p.setField(v.Field(j), val)
}
// check for ordering
if env.Order && len(os.Args) > order && !strings.HasPrefix(os.Args[order], "-") {
// assumption is that we take args in order present to populate
// the structure without using name flags {1} {2} {3} -blah
value, status = p.setField(v.Field(j), os.Args[order])
order++
}
// check for requiirement
if env.Require && !status {
fmt.Fprintf(os.Stderr, "%s: missing required (%s) parameter\n",
filepath.Base(os.Args[0]), strings.ToLower(v.Type().Field(j).Name))
os.Exit(0)
}
// mirror field NAME:VALUE from struct to the os.Environment table
if status && (p.SetENV || env.Environ) {
os.Setenv(name, value)
}
}
}
}
// setField supports the string, bool, int, int64, uint, uint64 types as
// well as types derived from them (eg. time.Duration is int64); otherwise
// the field is ignored as nothing can be set
func (p *Options) setField(v reflect.Value, s string) (string, bool) {
var ok bool
switch v.Kind() {
case reflect.String:
v.SetString(s)
ok = len(s) > 0
case reflect.Int, reflect.Int64:
n, _ := strconv.ParseInt(s, 10, 0)
v.SetInt(n)
ok = len(s) > 0 // accept 0 as valid
case reflect.Uint, reflect.Uint64:
n, _ := strconv.ParseUint(s, 10, 0)
v.SetUint(n)
ok = len(s) > 0 // accept 0 as valid
case reflect.Bool:
var value bool
switch strings.ToLower(s) {
//case "off", "no", "false", "0":
case "on", "yes", "ok", "true", "1":
value = true
fallthrough
default:
v.SetBool(value)
ok = true
}
//default:
// unsupported, no-op
}
if !ok {
s = ""
}
return s, ok
}