Skip to content

Commit 50b9067

Browse files
committed
encoding/openapi: wrap $ref in allOf when needed.
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 <[email protected]>
1 parent 4d31efd commit 50b9067

File tree

3 files changed

+51
-2
lines changed

3 files changed

+51
-2
lines changed

encoding/openapi/build.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,10 +1155,24 @@ func (b *builder) finish() *ast.StructLit {
11551155
t = &OrderedMap{}
11561156

11571157
case 1:
1158-
t = (*OrderedMap)(b.allOf[0])
1158+
hasRef := false
1159+
for _, e := range b.allOf[0].Elts {
1160+
if f, ok := e.(*ast.Field); ok {
1161+
name, _, _ := ast.LabelName(f.Label)
1162+
hasRef = hasRef || name == "$ref"
1163+
}
1164+
}
1165+
if !hasRef || b.singleFields == nil {
1166+
t = (*OrderedMap)(b.allOf[0])
1167+
break
1168+
}
1169+
fallthrough
11591170

11601171
default:
11611172
exprs := []ast.Expr{}
1173+
if t != nil {
1174+
exprs = append(exprs, (*ast.StructLit)(t))
1175+
}
11621176
for _, s := range b.allOf {
11631177
exprs = append(exprs, s)
11641178
}
@@ -1190,7 +1204,8 @@ func (b *builder) addConjunct(f func(*builder)) {
11901204
func (b *builder) addRef(v cue.Value, inst *cue.Instance, ref []string) {
11911205
name := b.ctx.makeRef(inst, ref)
11921206
b.addConjunct(func(b *builder) {
1193-
b.set("$ref", ast.NewString(path.Join("#", b.ctx.refPrefix, name)))
1207+
b.allOf = append(b.allOf, ast.NewStruct(
1208+
"$ref", ast.NewString(path.Join("#", b.ctx.refPrefix, name))))
11941209
})
11951210

11961211
if b.ctx.inst != inst {

encoding/openapi/testdata/refs.cue

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,11 @@
1111

1212
// ExcludedInt is not included in the output.
1313
#ExcludedInt: int
14+
15+
#Type: {
16+
a?: string
17+
#BaseType
18+
}
19+
#BaseType: {
20+
b: string
21+
}

encoding/openapi/testdata/refs.json

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@
77
"paths": {},
88
"components": {
99
"schemas": {
10+
"BaseType": {
11+
"type": "object",
12+
"required": [
13+
"b"
14+
],
15+
"properties": {
16+
"b": {
17+
"type": "string",
18+
"format": "string"
19+
}
20+
}
21+
},
1022
"Keep": {
1123
"type": "object",
1224
"required": [
@@ -30,6 +42,20 @@
3042
"type": "integer"
3143
}
3244
}
45+
},
46+
"Type": {
47+
"type": "object",
48+
"properties": {
49+
"a": {
50+
"type": "string",
51+
"format": "string"
52+
}
53+
},
54+
"allOf": [
55+
{
56+
"$ref": "#/components/schemas/BaseType"
57+
}
58+
]
3359
}
3460
}
3561
}

0 commit comments

Comments
 (0)