Skip to content

Commit

Permalink
Merge branch 'fork' into master
Browse files Browse the repository at this point in the history
Signed-off-by: Yousuf Jawwad <[email protected]>
  • Loading branch information
Yousuf Jawwad authored Apr 30, 2024
2 parents ad5eada + ecea152 commit f40ba29
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 5 deletions.
27 changes: 27 additions & 0 deletions pkg/codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ import (
"bytes"
"context"
"embed"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"runtime/debug"
"sort"
"strings"
Expand Down Expand Up @@ -134,6 +136,31 @@ func Generate(spec *openapi3.T, opts Configuration) (string, error) {
return "", fmt.Errorf("error parsing oapi-codegen templates: %w", err)
}

// load user-provided templates from directory. Will Override built-in versions.
if dir := opts.OutputOptions.UserTemplatesDir; dir != "" {
for _, tpl := range t.Templates() {
fp := path.Join(dir, tpl.Name())

_, err := os.Stat(fp)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("error accessing user-provided template %q: %w", fp, err)
}

if err == nil {
utpl := t.New(tpl.Name())
data, err := os.ReadFile(fp)

if err != nil {
return "", fmt.Errorf("error reading user-provided template %q: %w", fp, err)
}

if _, err := utpl.Parse(string(data)); err != nil {
return "", fmt.Errorf("error parsing user-provided template %q: %w", fp, err)
}
}
}
}

// load user-provided templates. Will Override built-in versions.
for name, template := range opts.OutputOptions.UserTemplates {
utpl := t.New(name)
Expand Down
1 change: 1 addition & 0 deletions pkg/codegen/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ type OutputOptions struct {
IncludeOperationIDs []string `yaml:"include-operation-ids,omitempty"` // Only include operations that have one of these operation-ids. Ignored when empty.
ExcludeOperationIDs []string `yaml:"exclude-operation-ids,omitempty"` // Exclude operations that have one of these operation-ids. Ignored when empty.
UserTemplates map[string]string `yaml:"user-templates,omitempty"` // Override built-in templates from user-provided files
UserTemplatesDir string `yaml:"user-templates-dir,omitempty"` // Override built-in tempolates from user-provided directory. Ignored when empty.

ExcludeSchemas []string `yaml:"exclude-schemas,omitempty"` // Exclude from generation schemas with given names. Ignored when empty.
ResponseTypeSuffix string `yaml:"response-type-suffix,omitempty"` // The suffix used for responses types
Expand Down
3 changes: 3 additions & 0 deletions pkg/codegen/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ const (
extEnumVarNames = "x-enum-varnames"
extEnumNames = "x-enumNames"
extDeprecationReason = "x-deprecated-reason"
// breu related schema extensions
extBreuEntity = "x-breu-entity"
extBreuEntityType = "x-breu-entity-type"
)

func extString(extPropValue interface{}) (string, error) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/codegen/merge_schemas_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func GenStructFromAllOf(allOf []*openapi3.SchemaRef, path []string) (string, err
return "", err
}
objectParts = append(objectParts, " // Embedded fields due to inline allOf schema")
objectParts = append(objectParts, GenFieldsFromProperties(goSchema.Properties)...)
objectParts = append(objectParts, GenFieldsFromProperties(goSchema.Properties, goSchema.BreuEntity, goSchema.BreuEntityType)...)

if goSchema.HasAdditionalProperties {
addPropsType := goSchema.AdditionalPropertiesType.GoType
Expand Down
33 changes: 29 additions & 4 deletions pkg/codegen/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ type Schema struct {
// Can be overriden by the OutputOptions#DisableTypeAliasesForType field
DefineViaAlias bool

// Breu related schema extensions
BreuEntity string // The name of the table this schema represents.
BreuEntityType string // type of db used. valid options are cql and sql.

// The original OpenAPIv3 Schema.
OAPISchema *openapi3.Schema
}
Expand Down Expand Up @@ -240,6 +244,20 @@ func GenerateGoSchema(sref *openapi3.SchemaRef, path []string) (Schema, error) {

schema := sref.Value

// Check if the breu entity and entity types exist.
// If they exist, load the corresponding values from thes schemas and return it.
entity := ""
entitype := ""

if extension, ok := schema.Extensions[extBreuEntity]; ok {
entity = extension.(string)
}

// Check for x-breu-entity-type
if extension, ok := schema.Extensions[extBreuEntityType]; ok {
entitype = extension.(string)
}

// If Ref is set on the SchemaRef, it means that this type is actually a reference to
// another type. We're not de-referencing, so simply use the referenced type.
if IsGoTypeReference(sref.Ref) {
Expand All @@ -258,8 +276,10 @@ func GenerateGoSchema(sref *openapi3.SchemaRef, path []string) (Schema, error) {
}

outSchema := Schema{
Description: schema.Description,
OAPISchema: schema,
Description: schema.Description,
OAPISchema: schema,
BreuEntity: entity,
BreuEntityType: entitype,
}

// AllOf is interesting, and useful. It's the union of a number of other
Expand Down Expand Up @@ -653,7 +673,7 @@ type FieldDescriptor struct {

// GenFieldsFromProperties produce corresponding field names with JSON annotations,
// given a list of schema descriptors
func GenFieldsFromProperties(props []Property) []string {
func GenFieldsFromProperties(props []Property, entity, entitype string) []string {
var fields []string
for i, p := range props {
field := ""
Expand Down Expand Up @@ -734,6 +754,11 @@ func GenFieldsFromProperties(props []Property) []string {
}
}

// Support x-breu-entity for cql types
if entity != "" && entitype == "cql" {
fieldTags["cql"] = p.JsonFieldName
}

// Support x-oapi-codegen-extra-tags
if extension, ok := p.Extensions[extPropExtraTags]; ok {
if tags, err := extExtraTags(extension); err == nil {
Expand Down Expand Up @@ -770,7 +795,7 @@ func GenStructFromSchema(schema Schema) string {
// Start out with struct {
objectParts := []string{"struct {"}
// Append all the field definitions
objectParts = append(objectParts, GenFieldsFromProperties(schema.Properties)...)
objectParts = append(objectParts, GenFieldsFromProperties(schema.Properties, schema.BreuEntity, schema.BreuEntityType)...)
// Close the struct
if schema.HasAdditionalProperties {
objectParts = append(objectParts,
Expand Down
39 changes: 39 additions & 0 deletions pkg/codegen/template_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"bytes"
"fmt"
"os"
"strconv"
"strings"
"text/template"

Expand Down Expand Up @@ -295,6 +296,41 @@ func stripNewLines(s string) string {
return r.Replace(s)
}

func split(sep, orig string) map[string]string {
parts := strings.Split(orig, sep)
res := make(map[string]string, len(parts))
for i, v := range parts {
res["_"+strconv.Itoa(i)] = v
}
return res
}

func splitn(sep string, n int, orig string) map[string]string {
parts := strings.SplitN(orig, sep, n)
res := make(map[string]string, len(parts))
for i, v := range parts {
res["_"+strconv.Itoa(i)] = v
}
return res
}

// substring creates a substring of the given string.
//
// If start is < 0, this calls string[:end].
//
// If start is >= 0 and end < 0 or end bigger than s length, this calls string[start:]
//
// Otherwise, this calls string[start, end].
func substring(start, end int, s string) string {
if start < 0 {
return s[:end]
}
if end < 0 || end > len(s) {
return s[start:]
}
return s[start:end]
}

// TemplateFunctions is passed to the template engine, and we can call each
// function here by keyName from the template code.
var TemplateFunctions = template.FuncMap{
Expand Down Expand Up @@ -322,4 +358,7 @@ var TemplateFunctions = template.FuncMap{
"stripNewLines": stripNewLines,
"sanitizeGoIdentity": SanitizeGoIdentity,
"toGoComment": StringWithTypeNameToGoComment,
"split": split,
"splitn": splitn,
"substring": substring,
}

0 comments on commit f40ba29

Please sign in to comment.