|
| 1 | +package docs |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "reflect" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | + |
| 10 | + schemaDocs "github.com/cloudquery/codegen/jsonschema/docs" |
| 11 | + "github.com/cloudquery/plugin-sdk/v4/schema" |
| 12 | + invoschema "github.com/invopop/jsonschema" |
| 13 | +) |
| 14 | + |
| 15 | +func TableOptionsDescriptionTransformer(tableOptions any, jsonSchema string) (schema.Transform, error) { |
| 16 | + var sc invoschema.Schema |
| 17 | + if err := json.Unmarshal([]byte(jsonSchema), &sc); err != nil { |
| 18 | + return nil, err |
| 19 | + } |
| 20 | + tableNamesToOptionsDocs := make(map[string]string) |
| 21 | + tableOptionsType := reflect.ValueOf(tableOptions).Elem().Type() |
| 22 | + for i := range tableOptionsType.NumField() { |
| 23 | + field := tableOptionsType.Field(i) |
| 24 | + fieldType := field.Type.String() |
| 25 | + if strings.Contains(fieldType, ".") { |
| 26 | + fieldType = strings.Split(fieldType, ".")[1] |
| 27 | + } |
| 28 | + defValue, ok := sc.Definitions[fieldType] |
| 29 | + if !ok { |
| 30 | + return nil, errors.New("definition not found for " + field.Name) |
| 31 | + } |
| 32 | + tableName := strings.Split(field.Tag.Get("json"), ",")[0] |
| 33 | + if tableName == "" { |
| 34 | + return nil, errors.New("json tag not found for table " + field.Name) |
| 35 | + } |
| 36 | + newRoot := sc |
| 37 | + newRoot.ID = "Table Options" |
| 38 | + newRoot.Ref = "#/$defs/" + "Table Options" |
| 39 | + newRoot.Definitions["Table Options"] = defValue |
| 40 | + sch, _ := json.Marshal(newRoot) |
| 41 | + doc, _ := schemaDocs.Generate(sch, 1) |
| 42 | + tocRegex := regexp.MustCompile(`# Table of contents[\s\S]+?##`) |
| 43 | + tableNamesToOptionsDocs[tableName] = tocRegex.ReplaceAllString(doc, "##") |
| 44 | + } |
| 45 | + |
| 46 | + return func(table *schema.Table) error { |
| 47 | + if tableNamesToOptionsDocs[table.Name] != "" { |
| 48 | + table.Description = table.Description + "\n\n" + tableNamesToOptionsDocs[table.Name] |
| 49 | + } |
| 50 | + return nil |
| 51 | + }, nil |
| 52 | +} |
0 commit comments