github.com/oam-dev/kubevela@v1.9.11/references/docgen/openapi.go (about) 1 /* 2 Copyright 2022 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package docgen 18 19 import ( 20 "bytes" 21 "fmt" 22 "strings" 23 24 "github.com/getkin/kin-openapi/openapi3" 25 "github.com/olekukonko/tablewriter" 26 ) 27 28 // GenerateConsoleDocument generate the document shown on the console. 29 func GenerateConsoleDocument(title string, schema *openapi3.Schema) (string, error) { 30 var buffer = &bytes.Buffer{} 31 var printSubProperties []*openapi3.Schema 32 if len(schema.Properties) > 0 { 33 var propertiesTable = tablewriter.NewWriter(buffer) 34 propertiesTable.SetHeader([]string{"NAME", "TYPE", "DESCRIPTION", "REQUIRED", "OPTIONS", "DEFAULT"}) 35 for key, subSchema := range schema.Properties { 36 name := subSchema.Value.Title 37 if title != "" { 38 name = fmt.Sprintf("(%s).%s", title, name) 39 } 40 defaultValue := fmt.Sprintf("%v", subSchema.Value.Default) 41 if subSchema.Value.Default == nil { 42 defaultValue = "" 43 } 44 var options = "" 45 for _, enum := range subSchema.Value.Enum { 46 options += fmt.Sprintf("%v", enum) 47 } 48 propertiesTable.Append([]string{ 49 name, 50 subSchema.Value.Type, 51 subSchema.Value.Description, 52 fmt.Sprintf("%t", strings.Contains(strings.Join(schema.Required, "/"), subSchema.Value.Title)), 53 options, 54 defaultValue, 55 }) 56 if len(subSchema.Value.Properties) > 0 { 57 printSubProperties = append(printSubProperties, schema.Properties[key].Value) 58 } 59 } 60 buffer.WriteString(title + "\n") 61 propertiesTable.Render() 62 } 63 64 for _, sub := range printSubProperties { 65 next := strings.Join([]string{title, sub.Title}, ".") 66 if title == "" { 67 next = sub.Title 68 } 69 re, err := GenerateConsoleDocument(next, sub) 70 if err != nil { 71 return "", err 72 } 73 buffer.WriteString(re) 74 } 75 76 return buffer.String(), nil 77 }