varsToStruct generates a Go struct from the configuration variables in the CollectionSpec.
(spec *ebpf.CollectionSpec, name, kind, comment string, embeds []string)
| 45 | // varsToStruct generates a Go struct from the configuration variables in the |
| 46 | // CollectionSpec. |
| 47 | func varsToStruct(spec *ebpf.CollectionSpec, name, kind, comment string, embeds []string) (string, error) { |
| 48 | type field struct { |
| 49 | comment string |
| 50 | goName string |
| 51 | cName string |
| 52 | typ string |
| 53 | defValue string |
| 54 | } |
| 55 | |
| 56 | kind = "kind:" + kind |
| 57 | |
| 58 | fields := make([]field, 0, len(spec.Variables)) |
| 59 | |
| 60 | for n, v := range spec.Variables { |
| 61 | // Only consider variables in a specific config section to avoid interfering |
| 62 | // with unrelated objects. |
| 63 | if v.SectionName != config.Section { |
| 64 | continue |
| 65 | } |
| 66 | |
| 67 | // DECLARE_CONFIG prefixes the variable name with a well-known prefix to |
| 68 | // avoid collisions with other variables with common names. |
| 69 | n = strings.TrimPrefix(n, config.ConstantPrefix) |
| 70 | |
| 71 | if v.Type == nil { |
| 72 | return "", fmt.Errorf("variable %s has no type information, was the ELF built without BTF?", n) |
| 73 | } |
| 74 | |
| 75 | // Skip variables that don't have the requested kind. |
| 76 | tags := v.Type.Tags |
| 77 | if !slices.Contains(tags, kind) { |
| 78 | continue |
| 79 | } |
| 80 | |
| 81 | // Pop the kind tag from the list of tags, we don't want to render it out |
| 82 | // to the config struct. |
| 83 | tags = slices.DeleteFunc(tags, func(s string) bool { return s == kind }) |
| 84 | |
| 85 | if len(tags) == 0 || tags[0] == "" { |
| 86 | return "", fmt.Errorf("variable %s has no doc comment", n) |
| 87 | } |
| 88 | |
| 89 | typ, err := btfVarGoType(v.Type) |
| 90 | if err != nil { |
| 91 | return "", fmt.Errorf("variable %s: getting Go type: %w", n, err) |
| 92 | } |
| 93 | |
| 94 | comment, err := tagsToComment(tags) |
| 95 | if err != nil { |
| 96 | return "", fmt.Errorf("variable %s: converting tags to comments: %w", n, err) |
| 97 | } |
| 98 | |
| 99 | defValue, err := varGoValue(v) |
| 100 | if err != nil { |
| 101 | return "", fmt.Errorf("variable %s: getting default Go value: %w", n, err) |
| 102 | } |
| 103 | |
| 104 | fields = append(fields, field{comment, camelCase(n), n, typ, goValueLiteral(defValue)}) |
no test coverage detected
searching dependent graphs…