cosmossdk.io/client/v2@v2.0.0-beta.1/autocli/flag/enum.go (about)

     1  package flag
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"google.golang.org/protobuf/reflect/protoreflect"
     9  
    10  	"cosmossdk.io/client/v2/internal/strcase"
    11  )
    12  
    13  type enumType struct {
    14  	enum protoreflect.EnumDescriptor
    15  }
    16  
    17  func (b enumType) NewValue(context.Context, *Builder) Value {
    18  	val := &enumValue{
    19  		enum:   b.enum,
    20  		valMap: map[string]protoreflect.EnumValueDescriptor{},
    21  	}
    22  	n := b.enum.Values().Len()
    23  	for i := 0; i < n; i++ {
    24  		valDesc := b.enum.Values().Get(i)
    25  		val.valMap[enumValueName(b.enum, valDesc)] = valDesc
    26  	}
    27  	return val
    28  }
    29  
    30  func (b enumType) DefaultValue() string {
    31  	defValue := ""
    32  	if def := b.enum.Values().ByNumber(0); def != nil {
    33  		defValue = enumValueName(b.enum, def)
    34  	}
    35  	return defValue
    36  }
    37  
    38  type enumValue struct {
    39  	enum   protoreflect.EnumDescriptor
    40  	value  protoreflect.EnumNumber
    41  	valMap map[string]protoreflect.EnumValueDescriptor
    42  }
    43  
    44  func (e enumValue) Get(protoreflect.Value) (protoreflect.Value, error) {
    45  	return protoreflect.ValueOfEnum(e.value), nil
    46  }
    47  
    48  func enumValueName(enum protoreflect.EnumDescriptor, enumValue protoreflect.EnumValueDescriptor) string {
    49  	name := string(enumValue.Name())
    50  	name = strings.TrimPrefix(name, strcase.ToScreamingSnake(string(enum.Name()))+"_")
    51  	return strcase.ToKebab(name)
    52  }
    53  
    54  func (e enumValue) String() string {
    55  	return enumValueName(e.enum, e.enum.Values().ByNumber(e.value))
    56  }
    57  
    58  func (e *enumValue) Set(s string) error {
    59  	valDesc, ok := e.valMap[s]
    60  	if !ok {
    61  		return fmt.Errorf("%s is not a valid value for enum %s", s, e.enum.FullName())
    62  	}
    63  	e.value = valDesc.Number()
    64  	return nil
    65  }
    66  
    67  func (e enumValue) Type() string {
    68  	var vals []string
    69  	n := e.enum.Values().Len()
    70  	for i := 0; i < n; i++ {
    71  		vals = append(vals, enumValueName(e.enum, e.enum.Values().Get(i)))
    72  	}
    73  	return fmt.Sprintf("%s (%s)", e.enum.Name(), strings.Join(vals, " | "))
    74  }