cosmossdk.io/client/v2@v2.0.0-beta.1/autocli/flag/binary.go (about) 1 package flag 2 3 import ( 4 "context" 5 "encoding/base64" 6 "encoding/hex" 7 "os" 8 9 "github.com/cockroachdb/errors" 10 "google.golang.org/protobuf/reflect/protoreflect" 11 ) 12 13 type binaryType struct{} 14 15 var _ Value = (*fileBinaryValue)(nil) 16 17 func (f binaryType) NewValue(context.Context, *Builder) Value { 18 return &fileBinaryValue{} 19 } 20 21 func (f binaryType) DefaultValue() string { 22 return "" 23 } 24 25 // fileBinaryValue is a Value that holds a binary file. 26 type fileBinaryValue struct { 27 value []byte 28 } 29 30 func (f *fileBinaryValue) Get(protoreflect.Value) (protoreflect.Value, error) { 31 return protoreflect.ValueOfBytes(f.value), nil 32 } 33 34 func (f *fileBinaryValue) String() string { 35 return string(f.value) 36 } 37 38 // Set implements the flag.Value interface for binary files, with exceptions. 39 // If the input string is a valid file path, the value will be the content of that file. 40 // If the input string is a valid hex or base64 string, the value will be the decoded form of that string. 41 // If the input string is not a valid file path, hex string, or base64 string, Set will return an error. 42 func (f *fileBinaryValue) Set(s string) error { 43 if data, err := os.ReadFile(s); err == nil { 44 f.value = data 45 return nil 46 } 47 48 if data, err := hex.DecodeString(s); err == nil { 49 f.value = data 50 return nil 51 } 52 53 if data, err := base64.StdEncoding.DecodeString(s); err == nil { 54 f.value = data 55 return nil 56 } 57 58 return errors.New("input string is neither a valid file path, hex, or base64 encoded") 59 } 60 61 func (f *fileBinaryValue) Type() string { 62 return "binary" 63 }