MCPcopy Create free account
hub / github.com/apache/devlake / DecodeStruct

Function DecodeStruct

backend/helpers/pluginhelper/api/config_util.go:33–93  ·  view source on GitHub ↗

DecodeStruct validates `input` struct with `validator` and set it into viper `tag` represent the fields when setting config, and the fields with `tag` shall prevail. `input` must be a pointer

(output *viper.Viper, input interface{}, data map[string]interface{}, tag string)

Source from the content-addressed store, hash-verified

31// `tag` represent the fields when setting config, and the fields with `tag` shall prevail.
32// `input` must be a pointer
33func DecodeStruct(output *viper.Viper, input interface{}, data map[string]interface{}, tag string) errors.Error {
34 // update fields from request body
35 err := Decode(data, input, validator.New())
36 if err != nil {
37 return err
38 }
39
40 vf := reflect.ValueOf(input)
41 if vf.Kind() != reflect.Ptr {
42 return errors.Default.New(fmt.Sprintf("input %v is not a pointer", input))
43 }
44
45 for _, f := range utils.WalkFields(reflect.Indirect(vf).Type(), nil) {
46 fieldName := f.Name
47 fieldType := f.Type
48 fieldTag := f.Tag.Get(tag)
49
50 // Check if the first letter is uppercase (indicates a public element, accessible)
51 ascii := rune(fieldName[0])
52 if int(ascii) < int('A') || int(ascii) > int('Z') {
53 continue
54 }
55
56 // View their tags in order to filter out members who don't have a valid tag set
57 if fieldTag == "" {
58 continue
59 }
60 vfField := vf.Elem().FieldByName(fieldName)
61 switch fieldType.Kind() {
62 case reflect.String:
63 output.Set(fieldTag, vfField.String())
64 case reflect.Int, reflect.Int64:
65 output.Set(fieldTag, vfField.Int())
66 case reflect.Float64, reflect.Float32:
67 output.Set(fieldTag, vfField.Float())
68 case reflect.Bool:
69 output.Set(fieldTag, vfField.Bool())
70 case reflect.Slice:
71 elemType := vfField.Type().Elem().Kind()
72 switch elemType {
73 case reflect.String:
74 output.Set(fieldTag, vfField.Interface().([]string))
75 case reflect.Int:
76 output.Set(fieldTag, vfField.Interface().([]int))
77 }
78 case reflect.Map:
79 keyType := vfField.Type().Key().Kind()
80 elemType := vfField.Type().Elem().Kind()
81 if keyType == reflect.String {
82 switch elemType {
83 case reflect.String:
84 output.Set(fieldTag, vfField.Interface().(map[string]string))
85 case reflect.Interface:
86 output.Set(fieldTag, vfField.Interface().(map[string]interface{}))
87 }
88 }
89 default:
90 }

Callers 4

TestSaveToConfigFunction · 0.85
TestLoadFromConfigFunction · 0.85

Calls 4

DecodeFunction · 0.70
NewMethod · 0.65
GetMethod · 0.65
StringMethod · 0.45

Tested by 4

TestSaveToConfigFunction · 0.68
TestLoadFromConfigFunction · 0.68