github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/utils/strings.go (about) 1 package utils 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "path/filepath" 9 10 "github.com/golang/protobuf/jsonpb" 11 "github.com/golang/protobuf/proto" 12 sig_yaml "sigs.k8s.io/yaml" 13 14 "github.com/mitchellh/mapstructure" 15 ) 16 17 // Serialize an interface using JSON or return error string 18 func Introspect(v interface{}) string { 19 bytes, err := json.MarshalIndent(v, "", " ") 20 if err != nil { 21 return fmt.Sprintf("Error: %s", err.Error()) 22 } else { 23 return string(bytes) 24 } 25 } 26 27 func CleanPath(path string) string { 28 return filepath.Clean(path) 29 } 30 31 func MapStruct[T any](source interface{}, dest *T) error { 32 return mapstructure.Decode(source, dest) 33 } 34 35 func SafelyGetValue[T any](target *T) T { 36 var vi T 37 if target != nil { 38 vi = *target 39 } 40 41 return vi 42 } 43 44 func IsEmptyString(s string) bool { 45 return s == "" 46 } 47 48 func ToPbJson[T proto.Message](obj T, indent string) (string, error) { 49 m := jsonpb.Marshaler{Indent: indent, OrigName: true} 50 return m.MarshalToString(obj) 51 } 52 53 func FromPbJson[T proto.Message](reader io.Reader, obj T) error { 54 return jsonpb.Unmarshal(reader, obj) 55 } 56 57 func FromYamlToPb[T proto.Message](reader io.Reader, obj T) error { 58 buf := new(bytes.Buffer) 59 _, err := buf.ReadFrom(reader) 60 if err != nil { 61 return err 62 } 63 64 jsonData, err := sig_yaml.YAMLToJSON(buf.Bytes()) 65 if err != nil { 66 return err 67 } 68 69 return jsonpb.Unmarshal(bytes.NewReader(jsonData), obj) 70 } 71 72 func FromPbToYaml[T proto.Message](writer io.Writer, obj T) error { 73 jsonData, err := ToPbJson(obj, "") 74 if err != nil { 75 return err 76 } 77 78 yamlData, err := sig_yaml.JSONToYAML([]byte(jsonData)) 79 if err != nil { 80 return err 81 } 82 83 _, err = writer.Write(yamlData) 84 if err != nil { 85 return err 86 } 87 88 return nil 89 }