-
Notifications
You must be signed in to change notification settings - Fork 24
/
usage.go
63 lines (58 loc) · 1.79 KB
/
usage.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
// Copyright (c) 2023, The Emergent Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package econfig
import (
"fmt"
"reflect"
"strings"
"cogentcore.org/core/reflectx"
)
// Usage returns the usage string for args based on given Config object
func Usage(cfg any) string {
var b strings.Builder
b.WriteString("The following command-line arguments set fields on the Config struct.\n")
b.WriteString("args are case insensitive and kebab-case or snake_case also works\n")
b.WriteString("most can be used without nesting path (e.g. -nepochs instead of -run.nepochs)\n")
b.WriteString("\n")
b.WriteString("-help or -h\tshow available command-line arguments and exit\n")
b.WriteString("-config or -cfg\tspecify filename for loading Config settings\n")
b.WriteString("\n")
usageStruct(cfg, "", &b)
return b.String()
}
// usageStruct adds usage info to given strings.Builder
func usageStruct(obj any, path string, b *strings.Builder) {
typ := reflectx.NonPointerType(reflect.TypeOf(obj))
val := reflectx.NonPointerValue(reflect.ValueOf(obj))
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
fv := val.Field(i)
if reflectx.NonPointerType(f.Type).Kind() == reflect.Struct {
nwPath := f.Name
if path != "" {
nwPath = path + "." + nwPath
}
usageStruct(reflectx.PointerValue(fv).Interface(), nwPath, b)
continue
}
nm := f.Name
if nm == "Includes" {
continue
}
if path != "" {
nm = path + "." + nm
}
b.WriteString(fmt.Sprintf("-%s\n", nm))
desc, ok := f.Tag.Lookup("desc")
if ok && desc != "" {
b.WriteString("\t")
b.WriteString(desc)
def, ok := f.Tag.Lookup("def")
if ok && def != "" {
b.WriteString(fmt.Sprintf(" (default %s)", def))
}
}
b.WriteString("\n")
}
}