-
Notifications
You must be signed in to change notification settings - Fork 0
/
scalar.go
50 lines (43 loc) · 1.09 KB
/
scalar.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
package flag_types
import (
"fmt"
"reflect"
"github.com/spf13/pflag"
"google.golang.org/protobuf/proto"
preflect "google.golang.org/protobuf/reflect/protoreflect"
)
type ScalarVar struct {
FdPath []preflect.FieldDescriptor
DVals []interface{}
Fd preflect.FieldDescriptor
Msg proto.Message
Tp reflect.Type
}
var _ pflag.Value = (*ScalarVar)(nil)
func (v *ScalarVar) String() string {
rawValue, present := getCurrentRawValue(v.Msg, v.FdPath)
if !present {
return fmt.Sprint(reflect.New(v.Tp))
}
return fmt.Sprintf("%v", rawValue)
}
func (v *ScalarVar) Set(raw string) error {
val, err := makeProtoValue(raw, v.Fd, v.Tp)
if err != nil {
return err
}
pathDefaults, pathFds := stripPathToLast(v.DVals, v.FdPath)
currentMsg := getFieldHolderAndEnsurePath(v.Msg, pathDefaults, pathFds)
currentMsg.Set(v.Fd, val)
return nil
}
func (v *ScalarVar) Type() string {
switch v.Fd.Kind() {
case preflect.GroupKind, preflect.MessageKind:
return string(v.Fd.Message().Name())
case preflect.EnumKind:
return string(v.Fd.Enum().Name())
default:
return v.Fd.Kind().String()
}
}