Skip to content
This repository has been archived by the owner on Nov 18, 2021. It is now read-only.

Commit

Permalink
encoding/openapi: wrap $ref in allOf when needed.
Browse files Browse the repository at this point in the history
It is unclear to me what the JSON schema spec says (and it
seems the current behavior is correct), but at least OpenAPI
expects $ref to be by itself.

Change-Id: Ic91f21eb16b1de342b99722ee45a91fb8844ed1a
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/6344
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
  • Loading branch information
mpvl committed Jun 16, 2020
1 parent 4d31efd commit 50b9067
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
19 changes: 17 additions & 2 deletions encoding/openapi/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -1155,10 +1155,24 @@ func (b *builder) finish() *ast.StructLit {
t = &OrderedMap{}

case 1:
t = (*OrderedMap)(b.allOf[0])
hasRef := false
for _, e := range b.allOf[0].Elts {
if f, ok := e.(*ast.Field); ok {
name, _, _ := ast.LabelName(f.Label)
hasRef = hasRef || name == "$ref"
}
}
if !hasRef || b.singleFields == nil {
t = (*OrderedMap)(b.allOf[0])
break
}
fallthrough

default:
exprs := []ast.Expr{}
if t != nil {
exprs = append(exprs, (*ast.StructLit)(t))
}
for _, s := range b.allOf {
exprs = append(exprs, s)
}
Expand Down Expand Up @@ -1190,7 +1204,8 @@ func (b *builder) addConjunct(f func(*builder)) {
func (b *builder) addRef(v cue.Value, inst *cue.Instance, ref []string) {
name := b.ctx.makeRef(inst, ref)
b.addConjunct(func(b *builder) {
b.set("$ref", ast.NewString(path.Join("#", b.ctx.refPrefix, name)))
b.allOf = append(b.allOf, ast.NewStruct(
"$ref", ast.NewString(path.Join("#", b.ctx.refPrefix, name))))
})

if b.ctx.inst != inst {
Expand Down
8 changes: 8 additions & 0 deletions encoding/openapi/testdata/refs.cue
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@

// ExcludedInt is not included in the output.
#ExcludedInt: int

#Type: {
a?: string
#BaseType
}
#BaseType: {
b: string
}
26 changes: 26 additions & 0 deletions encoding/openapi/testdata/refs.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@
"paths": {},
"components": {
"schemas": {
"BaseType": {
"type": "object",
"required": [
"b"
],
"properties": {
"b": {
"type": "string",
"format": "string"
}
}
},
"Keep": {
"type": "object",
"required": [
Expand All @@ -30,6 +42,20 @@
"type": "integer"
}
}
},
"Type": {
"type": "object",
"properties": {
"a": {
"type": "string",
"format": "string"
}
},
"allOf": [
{
"$ref": "#/components/schemas/BaseType"
}
]
}
}
}
Expand Down

0 comments on commit 50b9067

Please sign in to comment.