Debian Codegraph @

v2/enum.go

raw symbols SCIP
1 // Copyright 2017 Google Inc. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package getopt
6
7 import (
8 "errors"
9 "fmt"
10 "sync"
11 )
12
13 type enumValue string
14
15 var (
16 enumValuesMu sync.Mutex
17 enumValues = make(map[*enumValue]map[string]struct{})
18 )
19
20 func (s *enumValue) Set(value string, opt Option) error {
21 enumValuesMu.Lock()
22 es, ok := enumValues[s]
23 enumValuesMu.Unlock()
24 if !ok || es == nil {
25 return errors.New("this option has no values")
26 }
27 if _, ok := es[value]; !ok {
28 return errors.New("invalid value: " + value)
29 }
30 *s = enumValue(value)
31 return nil
32 }
33
34 func (s *enumValue) String() string {
35 return string(*s)
36 }
37
38 // Enum creates an option that can only be set to one of the enumerated strings
39 // passed in values. Passing nil or an empty slice results in an option that
40 // will always fail. If not "", value is the default value of the enum. If
41 // value is not listed in values then Enum will produce an error on standard
42 // error and then exit the program with a status of 1.
43 func Enum(name rune, values []string, value string, helpvalue ...string) *string {
44 return CommandLine.Enum(name, values, value, helpvalue...)
45 }
46
47 func (s *Set) Enum(name rune, values []string, value string, helpvalue ...string) *string {
48 var p enumValue
49 p.define(values, value, &option{short: name})
50 s.FlagLong(&p, "", name, helpvalue...)
51 return (*string)(&p)
52 }
53
54 func EnumLong(name string, short rune, values []string, value string, helpvalue ...string) *string {
55 return CommandLine.EnumLong(name, short, values, value, helpvalue...)
56 }
57
58 func (s *Set) EnumLong(name string, short rune, values []string, value string, helpvalue ...string) *string {
59 var p enumValue
60 p.define(values, value, &option{short: short, long: name})
61 s.FlagLong(&p, name, short, helpvalue...)
62 return (*string)(&p)
63 }
64
65 func (e *enumValue) define(values []string, def string, opt Option) {
66 m := make(map[string]struct{})
67 for _, v := range values {
68 m[v] = struct{}{}
69 }
70 enumValuesMu.Lock()
71 enumValues[e] = m
72 enumValuesMu.Unlock()
73 if def != "" {
74 if err := e.Set(def, nil); err != nil {
75 fmt.Fprintf(stderr, "setting default for %s: %v\n", opt.Name(), err)
76 exit(1)
77 }
78 }
79 }