File: flagset.go

package info (click to toggle)
golang-github-voxelbrain-goptions 2.5.11-2.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 168 kB
  • sloc: makefile: 2
file content (240 lines) | stat: -rw-r--r-- 5,908 bytes parent folder | download | duplicates (3)
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
package goptions

import (
	"errors"
	"fmt"
	"io"
	"os"
	"reflect"
	"strings"
	"sync"
)

// A FlagSet represents one set of flags which belong to one particular program.
// A FlagSet is also used to represent a subset of flags belonging to one verb.
type FlagSet struct {
	// This HelpFunc will be called when PrintHelp() is called.
	HelpFunc
	// Name of the program. Might be used by HelpFunc.
	Name          string
	helpFlag      *Flag
	remainderFlag *Flag
	shortMap      map[string]*Flag
	longMap       map[string]*Flag
	verbFlag      *Flag
	// Global option flags
	Flags []*Flag
	// Verbs and corresponding FlagSets
	Verbs  map[string]*FlagSet
	parent *FlagSet
}

// NewFlagSet returns a new FlagSet containing all the flags which result from
// parsing the tags of the struct. Said struct as to be passed to the function
// as a pointer.
// If a tag line is erroneous, NewFlagSet() panics as this is considered a
// compile time error rather than a runtme error.
func NewFlagSet(name string, v interface{}) *FlagSet {
	structValue := reflect.ValueOf(v)
	if structValue.Kind() != reflect.Ptr {
		panic("Value type is not a pointer to a struct")
	}
	structValue = structValue.Elem()
	if structValue.Kind() != reflect.Struct {
		panic("Value type is not a pointer to a struct")
	}
	return newFlagset(name, structValue, nil)
}

// Internal version which skips type checking and takes the "parent"'s
// remainder flag as a parameter.
func newFlagset(name string, structValue reflect.Value, parent *FlagSet) *FlagSet {
	var once sync.Once
	r := &FlagSet{
		Name:     name,
		Flags:    make([]*Flag, 0),
		HelpFunc: DefaultHelpFunc,
		parent:   parent,
	}

	if parent != nil && parent.remainderFlag != nil {
		r.remainderFlag = parent.remainderFlag
	}

	var i int
	// Parse Option fields
	for i = 0; i < structValue.Type().NumField(); i++ {
		// Skip unexported fields
		if StartsWithLowercase(structValue.Type().Field(i).Name) {
			continue
		}

		fieldValue := structValue.Field(i)
		tag := structValue.Type().Field(i).Tag.Get("goptions")
		flag, err := parseStructField(fieldValue, tag)

		if err != nil {
			panic(fmt.Sprintf("Invalid struct field: %s", err))
		}
		if fieldValue.Type().Name() == "Verbs" {
			r.verbFlag = flag
			break
		}
		if fieldValue.Type().Name() == "Help" {
			r.helpFlag = flag
		}
		if fieldValue.Type().Name() == "Remainder" && r.remainderFlag == nil {
			r.remainderFlag = flag
		}

		if len(tag) != 0 {
			r.Flags = append(r.Flags, flag)
		}
	}

	// Parse verb fields
	for i++; i < structValue.Type().NumField(); i++ {
		once.Do(func() {
			r.Verbs = make(map[string]*FlagSet)
		})
		fieldValue := structValue.Field(i)
		tag := structValue.Type().Field(i).Tag.Get("goptions")
		r.Verbs[tag] = newFlagset(tag, fieldValue, r)
	}
	r.createMaps()
	return r
}

var (
	ErrHelpRequest = errors.New("Request for Help")
)

// Parse takes the command line arguments and sets the corresponding values
// in the FlagSet's struct.
func (fs *FlagSet) Parse(args []string) (err error) {
	// Parse global flags
	for len(args) > 0 {
		if !((isLong(args[0]) && fs.hasLongFlag(args[0][2:])) ||
			(isShort(args[0]) && fs.hasShortFlag(args[0][1:2]))) {
			break
		}
		f := fs.FlagByName(args[0])
		args, err = f.Parse(args)
		if err != nil {
			return
		}
		if f == fs.helpFlag && f.WasSpecified {
			return ErrHelpRequest
		}
	}

	// Process verb
	if len(args) > 0 {
		if verb, ok := fs.Verbs[args[0]]; ok {
			fs.verbFlag.value.Set(reflect.ValueOf(Verbs(args[0])))
			err := verb.Parse(args[1:])
			if err != nil {
				return err
			}
			args = args[0:0]
		}
	}

	// Process remainder
	if len(args) > 0 {
		if fs.remainderFlag == nil {
			return fmt.Errorf("Invalid trailing arguments: %v", args)
		}
		remainder := reflect.MakeSlice(fs.remainderFlag.value.Type(), len(args), len(args))
		reflect.Copy(remainder, reflect.ValueOf(args))
		fs.remainderFlag.value.Set(remainder)
	}

	// Check for unset, obligatory, single Flags
	for _, f := range fs.Flags {
		if f.Obligatory && !f.WasSpecified && len(f.MutexGroups) == 0 {
			return fmt.Errorf("%s must be specified", f.Name())
		}
	}

	// Check for multiple set Flags in one mutex group
	// Check also for unset, obligatory mutex groups
	mgs := fs.MutexGroups()
	for _, mg := range mgs {
		if !mg.IsValid() {
			return fmt.Errorf("Exactly one of %s must be specified", strings.Join(mg.Names(), ", "))
		}
	}
	return nil
}

func (fs *FlagSet) createMaps() {
	fs.longMap = make(map[string]*Flag)
	fs.shortMap = make(map[string]*Flag)
	for _, flag := range fs.Flags {
		fs.longMap[flag.Long] = flag
		fs.shortMap[flag.Short] = flag
	}
}

func (fs *FlagSet) hasLongFlag(fname string) bool {
	_, ok := fs.longMap[fname]
	return ok
}

func (fs *FlagSet) hasShortFlag(fname string) bool {
	_, ok := fs.shortMap[fname]
	return ok
}

func (fs *FlagSet) FlagByName(fname string) *Flag {
	if isShort(fname) && fs.hasShortFlag(fname[1:2]) {
		return fs.shortMap[fname[1:2]]
	} else if isLong(fname) && fs.hasLongFlag(fname[2:]) {
		return fs.longMap[fname[2:]]
	}
	return nil
}

// MutexGroups returns a map of Flag lists which contain mutually
// exclusive flags.
func (fs *FlagSet) MutexGroups() map[string]MutexGroup {
	r := make(map[string]MutexGroup)
	for _, f := range fs.Flags {
		for _, mg := range f.MutexGroups {
			if len(mg) == 0 {
				continue
			}
			if _, ok := r[mg]; !ok {
				r[mg] = make(MutexGroup, 0)
			}
			r[mg] = append(r[mg], f)
		}
	}
	return r
}

// Prints the FlagSet's help to the given writer.
func (fs *FlagSet) PrintHelp(w io.Writer) {
	fs.HelpFunc(w, fs)
}

func (fs *FlagSet) ParseAndFail(w io.Writer, args []string) {
	err := fs.Parse(args)
	if err != nil {
		errCode := 0
		if err != ErrHelpRequest {
			errCode = 1
			fmt.Fprintf(w, "Error: %s\n", err)
		}
		fs.PrintHelp(w)
		os.Exit(errCode)
	}
}

func StartsWithLowercase(s string) bool {
	if len(s) <= 0 {
		return false
	}
	return strings.ToLower(s)[0] == s[0]
}