Skip to content

Commit 78f915e

Browse files
fredbiclaude
andcommitted
fix(schema): swagger:model + override publishes a definition + $ref (F1/F2/F4, parts A+B)
Quirk F1/F2/F4 (doc-site-quirks.md). A named type carrying both swagger:model and a per-type override (swagger:strfmt / swagger:type / swagger:enum) used to inline the override on referencing fields while emitting a degenerate ORPHAN definition (strfmt: format dropped; enum: value-less; type: bare underlying), and never a $ref. Per the agreed unified rule, swagger:model is the opt-in to a first-class definition: WITH it the type publishes a definition carrying the FULL override schema and referencing fields $ref it; WITHOUT it an override type inlines as before. Two coordinated halves: * Part B (definition carries the override): buildFromDecl's named case runs the override classifiers (classifierNamedStructStrfmt / classifierNamedBasic) on the DEFINITION target, so the def gets {type:string,format:uuid} (F1) / the enum values (F4) instead of the bare-underlying orphan. swagger:type on the decl was already applied (F3's decl-site classifierNamedTypeOverride). * Part A (field site $ref): buildNamedType skips the inline override classifiers when the named type is swagger:model (decl.HasModelAnnotation()) and falls to the resolveRefOr $ref pivot. The override classifiers — and their diagnostics, e.g. the F8 swagger:alias deprecation — therefore run once, at definition build, not per reference. Corpus effect (the unified decision applied everywhere): existing swagger:model + override types flip inline -> $ref, several matching the fixtures' own stated intent — raw-message-override ("expect {$ref: AsArray/AsObject}"), swagger-type-array (StructWithBadType "falls through to makeRef"), named-struct-tags-ref (PhoneNumber "should bubble up as a $ref"), and the classification mods-strfmt date-time types. A bare $ref field drops inline field description / x-go-name (standard OAS2 — siblings need an allOf wrap; identical to every other $ref field; DescWithRef opts the description back in). Goldens regenerated; TestAliasedTypes / RawMessageOverride case-B assertions updated to $ref; the F1/F2/F4 witness flipped to the fixed expectations. NOT yet done — F4b: bare swagger:enum (no name) still parse-errors and collects no consts (witness carries TODO Part C). Lands next. * contributes go-swagger/go-swagger doc-site quirks F1, F2, F4 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
1 parent 1da0aeb commit 78f915e

8 files changed

Lines changed: 108 additions & 99 deletions

‎fixtures/integration/golden/enhancements_named_struct_tags-ref.json‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,16 @@
1919
"x-go-name": "ID"
2020
},
2121
"phone": {
22-
"type": "string",
23-
"format": "phone",
24-
"x-go-name": "Phone"
22+
"$ref": "#/definitions/PhoneNumber"
2523
}
2624
},
2725
"x-go-package": "github.com/go-openapi/codescan/fixtures/enhancements/named-struct-tags-ref"
2826
},
2927
"PhoneNumber": {
3028
"description": "Since we have added the explicit model annotation, we expect this definition\nto bubble up and appear as a $ref in the spec.",
31-
"type": "object",
29+
"type": "string",
30+
"format": "phone",
3231
"title": "PhoneNumber is a named struct annotated as a strfmt. When used as a\nfield type the scanner emits {type: \"string\", format: \"phone\"} via the\nstrfmt branch of buildNamedStruct.",
33-
"properties": {
34-
"CountryCode": {
35-
"type": "string"
36-
},
37-
"Number": {
38-
"type": "string"
39-
}
40-
},
4132
"x-go-package": "github.com/go-openapi/codescan/fixtures/enhancements/named-struct-tags-ref"
4233
}
4334
}

‎fixtures/integration/golden/enhancements_raw_message_override.json‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,10 @@
5353
"title": "TypedContainer (case B field reference) — references the wrappers.",
5454
"properties": {
5555
"arr": {
56-
"description": "Wrapped via AsArray — expect `{$ref: AsArray}` whose definition\nresolves to a typed array shape.",
57-
"type": "array",
58-
"items": {
59-
"type": "integer",
60-
"format": "uint8"
61-
},
62-
"x-go-name": "Arr"
56+
"$ref": "#/definitions/AsArray"
6357
},
6458
"obj": {
65-
"description": "Wrapped via AsObject — expect `{$ref: AsObject}` whose definition\nresolves to `{type: object}` (the classifier wins on the decl).",
66-
"type": "object",
67-
"x-go-name": "Obj"
59+
"$ref": "#/definitions/AsObject"
6860
}
6961
},
7062
"x-go-package": "github.com/go-openapi/codescan/fixtures/enhancements/raw-message-override"

‎fixtures/integration/golden/enhancements_swagger_type_array.json‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,7 @@
1313
"title": "Payload aggregates all four cases so a full scan walks every branch.",
1414
"properties": {
1515
"headers": {
16-
"description": "Headers for this request.",
17-
"type": "object",
18-
"x-go-name": "Headers"
16+
"$ref": "#/definitions/objectStruct"
1917
},
2018
"labels": {
2119
"description": "Labels for this item.",
@@ -26,15 +24,7 @@
2624
"x-go-name": "Labels"
2725
},
2826
"nested": {
29-
"description": "The nested struct with an unsupported swagger:type.",
30-
"type": "object",
31-
"properties": {
32-
"name": {
33-
"type": "string",
34-
"x-go-name": "Name"
35-
}
36-
},
37-
"x-go-name": "Nested"
27+
"$ref": "#/definitions/structWithBadType"
3828
},
3929
"tags": {
4030
"description": "Tags for this item.",

‎fixtures/integration/golden/quirk_model_override_matrix.json‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,16 @@
77
"title": "Holder references each override type to expose field-site rendering.",
88
"properties": {
99
"id": {
10-
"type": "string",
11-
"format": "uuid",
12-
"x-go-name": "ID"
10+
"$ref": "#/definitions/UUID"
1311
},
1412
"priority": {
1513
"$ref": "#/definitions/Priority"
1614
},
1715
"raw": {
18-
"type": "string",
19-
"x-go-name": "Raw"
16+
"$ref": "#/definitions/RawID"
2017
},
2118
"state": {
22-
"description": "active StatusActive is active.\nclosed StatusClosed is closed.",
23-
"type": "string",
24-
"enum": [
25-
"active",
26-
"closed"
27-
],
28-
"x-go-enum-desc": "active StatusActive is active.\nclosed StatusClosed is closed.",
29-
"x-go-name": "State"
19+
"$ref": "#/definitions/Status"
3020
}
3121
},
3222
"x-go-package": "github.com/go-openapi/codescan/fixtures/quirks/model-override-matrix"
@@ -46,11 +36,17 @@
4636
"Status": {
4737
"description": "Status is an enum type (named swagger:enum) with swagger:model (F4): values\ninline on referencing fields, or a $ref to an enum definition?",
4838
"type": "string",
39+
"enum": [
40+
"active",
41+
"closed"
42+
],
43+
"x-go-enum-desc": "active StatusActive is active.\nclosed StatusClosed is closed.",
4944
"x-go-package": "github.com/go-openapi/codescan/fixtures/quirks/model-override-matrix"
5045
},
5146
"UUID": {
5247
"description": "UUID is a string-format type carrying BOTH swagger:strfmt and swagger:model\n(F1): does it publish a {type:string,format:uuid} definition that fields\n$ref, or inline + an orphan definition?",
5348
"type": "string",
49+
"format": "uuid",
5450
"x-go-package": "github.com/go-openapi/codescan/fixtures/quirks/model-override-matrix"
5551
}
5652
}

‎internal/builders/schema/schema.go‎

Lines changed: 49 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,26 @@ func (s *Builder) buildFromDecl(schema *oaispec.Schema) error {
143143
if s.guardDecl(tpe) {
144144
return nil
145145
}
146+
// F1/F4: a swagger:model type carrying a swagger:strfmt or
147+
// swagger:enum override publishes the FULL override schema on its
148+
// own definition, not the bare-underlying orphan
149+
// ({type:string} with the format dropped / no enum values). The
150+
// override classifiers — the same ones the field site uses —
151+
// inline that schema onto the definition target here; field sites
152+
// then $ref the definition (see buildNamedType's swagger:model
153+
// gate). swagger:type is already applied above (decl-site
154+
// classifierNamedTypeOverride).
155+
defTgt := NewTypable(schema, 0, s.skipExtensions)
156+
switch ut := tpe.Underlying().(type) {
157+
case *types.Struct:
158+
if s.classifierNamedStructStrfmt(s.Decl.Comments, defTgt) {
159+
return nil
160+
}
161+
case *types.Basic:
162+
if s.classifierNamedBasic(s.Decl.Comments, s.Decl.Pkg, ut, defTgt) {
163+
return nil
164+
}
165+
}
146166
ti := s.Decl.Pkg.TypesInfo.Types[s.Decl.Spec.Type]
147167
resolvers.MustBeAType(ti) // invariant
148168
return s.buildFromType(ti.Type, NewTypable(schema, 0, s.skipExtensions))
@@ -393,15 +413,25 @@ func (s *Builder) buildNamedType(titpe *types.Named, target ifaces.SwaggerTypabl
393413
}
394414

395415
var cmt *ast.CommentGroup
416+
var isModel bool
396417
if decl, ok := s.Ctx.DeclForType(titpe); ok && decl != nil {
397418
cmt = decl.Comments
398-
}
399-
400-
if handled, recurse := s.classifierNamedTypeOverride(cmt, target, titpe, s.Ctx.PosOf(tio.Pos())); handled {
401-
if recurse {
402-
return s.buildFromType(titpe.Underlying(), target)
419+
// A swagger:model type carrying an override (strfmt/type/enum)
420+
// publishes its override schema on its OWN definition (applied at
421+
// buildFromDecl) and is referenced here by $ref — the inline
422+
// override classifiers below are skipped so they neither inline
423+
// nor re-emit their diagnostics (F1/F2/F4). Without swagger:model,
424+
// an override type inlines as before.
425+
isModel = decl.HasModelAnnotation()
426+
}
427+
428+
if !isModel {
429+
if handled, recurse := s.classifierNamedTypeOverride(cmt, target, titpe, s.Ctx.PosOf(tio.Pos())); handled {
430+
if recurse {
431+
return s.buildFromType(titpe.Underlying(), target)
432+
}
433+
return nil
403434
}
404-
return nil
405435
}
406436

407437
// Dissolve when there's no source-level TypeSpec to $ref:
@@ -416,7 +446,7 @@ func (s *Builder) buildNamedType(titpe *types.Named, target ifaces.SwaggerTypabl
416446
// Underlying-shape table. See [§dispatch-table](./README.md#dispatch-table).
417447
switch utitpe := titpe.Underlying().(type) {
418448
case *types.Struct:
419-
if s.classifierNamedStructStrfmt(cmt, target) {
449+
if !isModel && s.classifierNamedStructStrfmt(cmt, target) {
420450
return nil
421451
}
422452
return s.resolveRefOr(tio, target, nil)
@@ -429,17 +459,17 @@ func (s *Builder) buildNamedType(titpe *types.Named, target ifaces.SwaggerTypabl
429459
s.Warn("skipped unsupported builtin", slog.Any("type", tio))
430460
return nil
431461
}
432-
if s.classifierNamedBasic(cmt, pkg, utitpe, target) {
462+
if !isModel && s.classifierNamedBasic(cmt, pkg, utitpe, target) {
433463
return nil
434464
}
435465
return s.resolveRefOr(tio, target, func() error {
436466
return resolvers.SwaggerSchemaForType(utitpe.String(), target)
437467
})
438468

439469
case *types.Array:
440-
return s.buildNamedArrayLike(tio, cmt, utitpe.Elem(), target, false)
470+
return s.buildNamedArrayLike(tio, cmt, utitpe.Elem(), target, false, isModel)
441471
case *types.Slice:
442-
return s.buildNamedArrayLike(tio, cmt, utitpe.Elem(), target, true)
472+
return s.buildNamedArrayLike(tio, cmt, utitpe.Elem(), target, true, isModel)
443473

444474
case *types.Map:
445475
return s.resolveRefOr(tio, target, nil)
@@ -452,12 +482,16 @@ func (s *Builder) buildNamedType(titpe *types.Named, target ifaces.SwaggerTypabl
452482

453483
// buildNamedArrayLike is the unified Array/Slice arm.
454484
// forSlice toggles the slice-only "bsonobjectid" special case in classifierNamedArrayLike.
455-
func (s *Builder) buildNamedArrayLike(tio *types.TypeName, cmt *ast.CommentGroup, elem types.Type, tgt ifaces.SwaggerTypable, forSlice bool) error {
456-
if handled, recurse := s.classifierNamedArrayLike(cmt, tgt, forSlice); handled {
457-
if recurse {
458-
return s.buildFromType(elem, tgt.Items())
485+
// isModel skips the inline override classifier so a swagger:model array/slice
486+
// type is referenced by $ref (its override schema lives on its own definition).
487+
func (s *Builder) buildNamedArrayLike(tio *types.TypeName, cmt *ast.CommentGroup, elem types.Type, tgt ifaces.SwaggerTypable, forSlice, isModel bool) error {
488+
if !isModel {
489+
if handled, recurse := s.classifierNamedArrayLike(cmt, tgt, forSlice); handled {
490+
if recurse {
491+
return s.buildFromType(elem, tgt.Items())
492+
}
493+
return nil
459494
}
460-
return nil
461495
}
462496

463497
return s.resolveRefOr(tio, tgt, func() error {

‎internal/builders/schema/schema_test.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -682,19 +682,23 @@ func TestAliasedTypes(t *testing.T) {
682682

683683
scantest.AssertRef(t, &schema, "modsNamed", "ModsNamed", "#/definitions/modsSomeStringType")
684684
scantest.AssertRef(t, &schema, "modsNumbered", "ModsNumbered", "#/definitions/modsSomeIntType")
685-
scantest.AssertProperty(t, &schema, "string", "modsDated", "date-time", "ModsDated")
685+
// F1: modsSomeTimeType is swagger:model + swagger:strfmt date-time, so it
686+
// now $refs its definition (which carries the format) like its siblings,
687+
// rather than inlining {string,date-time}.
688+
scantest.AssertRef(t, &schema, "modsDated", "ModsDated", "#/definitions/modsSomeTimeType")
686689
scantest.AssertRef(t, &schema, "modsTimed", "ModsTimed", "#/definitions/modsSomeTimedType")
687690
scantest.AssertRef(t, &schema, "modsPetted", "ModsPetted", "#/definitions/modsSomePettedType")
688691

689692
assertArrayRef(t, &schema, "modsNameds", "ModsNameds", "#/definitions/modsSomeStringType")
690693
assertArrayRef(t, &schema, "modsNumbereds", "ModsNumbereds", "#/definitions/modsSomeIntType")
691-
scantest.AssertArrayProperty(t, &schema, "string", "modsDateds", "date-time", "ModsDateds")
694+
assertArrayRef(t, &schema, "modsDateds", "ModsDateds", "#/definitions/modsSomeTimeType")
692695
assertArrayRef(t, &schema, "modsTimeds", "ModsTimeds", "#/definitions/modsSomeTimedType")
693696
assertArrayRef(t, &schema, "modsPetteds", "ModsPetteds", "#/definitions/modsSomePettedType")
694697

695698
scantest.AssertRef(t, &schema, "manyModsNamed", "ManyModsNamed", "#/definitions/modsSomeStringsType")
696699
scantest.AssertRef(t, &schema, "manyModsNumbered", "ManyModsNumbered", "#/definitions/modsSomeIntsType")
697-
scantest.AssertArrayProperty(t, &schema, "string", "manyModsDated", "date-time", "ManyModsDated")
700+
// F1: modsSomeTimesType (model + strfmt date-time) now $refs its definition.
701+
scantest.AssertRef(t, &schema, "manyModsDated", "ManyModsDated", "#/definitions/modsSomeTimesType")
698702
scantest.AssertRef(t, &schema, "manyModsTimed", "ManyModsTimed", "#/definitions/modsSomeTimedsType")
699703
scantest.AssertRef(t, &schema, "manyModsPetted", "ManyModsPetted", "#/definitions/modsSomePettedsType")
700704
scantest.AssertRef(t, &schema, "manyModsPettedPtr", "ManyModsPettedPtr", "#/definitions/modsSomePettedsPtrType")

‎internal/integration/coverage_enhancements_test.go‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -264,16 +264,19 @@ func TestCoverage_RawMessageOverride(t *testing.T) {
264264
def, ok := defs["TypedContainer"]
265265
require.TrueT(t, ok)
266266

267+
// F2: AsObject / AsArray carry swagger:type + swagger:model, so the
268+
// fields $ref their definitions (which hold the overridden shape) —
269+
// matching the fixture's stated "expect {$ref: ...}" intent, rather
270+
// than inlining the override at the field site.
267271
obj, ok := def.Properties["obj"]
268272
require.TrueT(t, ok)
269-
assert.TrueT(t, obj.Type.Contains("object"), "obj should be typed object via swagger:type on AsObject")
273+
objRef := obj.Ref
274+
assert.EqualT(t, "#/definitions/AsObject", objRef.String())
270275

271276
arr, ok := def.Properties["arr"]
272277
require.TrueT(t, ok)
273-
assert.TrueT(t, arr.Type.Contains("array"), "arr should be typed array via swagger:type on AsArray")
274-
require.NotNil(t, arr.Items)
275-
require.NotNil(t, arr.Items.Schema)
276-
assert.TrueT(t, arr.Items.Schema.Type.Contains("integer"), "array items reflect []byte → uint8")
278+
arrRef := arr.Ref
279+
assert.EqualT(t, "#/definitions/AsArray", arrRef.String())
277280
})
278281

279282
t.Run("case B': wrapper-type top-level definitions honour swagger:type", func(t *testing.T) {

‎internal/integration/coverage_quirk_model_override_test.go‎

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,15 @@ import (
1313
"github.com/go-openapi/testify/v2/require"
1414
)
1515

16-
// TestQuirk_ModelOverrideMatrix is the F1/F2/F4 WITNESS (documented-current,
17-
// post-F3): how swagger:model combined with a per-type override
18-
// (swagger:strfmt / swagger:type / swagger:enum) renders today. No fix — the
19-
// golden quirk_model_override_matrix.json is the baseline the reconciliation
20-
// is measured against. The TODO markers flag what should change: each override
21-
// type should publish a first-class definition carrying the FULL override
22-
// schema, and referencing fields should $ref it (instead of inlining + an
23-
// orphan, degenerate definition).
16+
// TestQuirk_ModelOverrideMatrix verifies the F1/F2/F4 reconciliation: a
17+
// swagger:model type carrying a per-type override (swagger:strfmt / swagger:type
18+
// / swagger:enum) now publishes a first-class definition carrying the FULL
19+
// override schema, and referencing fields $ref it (instead of inlining + an
20+
// orphan, degenerate definition). The golden quirk_model_override_matrix.json
21+
// captures the fixed shape.
22+
//
23+
// F4b (bare swagger:enum const collection) is NOT yet done — its assertions
24+
// carry TODO Part C and still pin the current (no-enum) behaviour.
2425
func TestQuirk_ModelOverrideMatrix(t *testing.T) {
2526
var diags []grammar.Diagnostic
2627
doc, err := codescan.Run(&codescan.Options{
@@ -35,42 +36,40 @@ func TestQuirk_ModelOverrideMatrix(t *testing.T) {
3536
h := doc.Definitions["Holder"].Properties
3637
require.NotNil(t, h)
3738

38-
// TODO F1: strfmt+model inlines {string,uuid} on the field; the UUID
39-
// definition is an orphan {type:string} with the format DROPPED. Should
40-
// be a {string,format:uuid} definition the field $refs.
39+
// F1: strfmt+model — field $refs UUID; the UUID definition carries the
40+
// format ({type:string, format:uuid}), no longer an orphan.
4141
id := h["id"]
42-
assert.Equal(t, []string{"string"}, []string(id.Type))
43-
assert.Equal(t, "uuid", id.Format)
44-
assert.Empty(t, id.Ref.String(), "TODO F1: field should $ref UUID")
45-
assert.Empty(t, doc.Definitions["UUID"].Format, "TODO F1: definition drops the format today")
42+
assert.Equal(t, "#/definitions/UUID", id.Ref.String())
43+
assert.Empty(t, id.Type, "field is a $ref, not an inlined scalar")
44+
assert.Equal(t, "uuid", doc.Definitions["UUID"].Format)
4645

47-
// TODO F2: type+model inlines {string} on the field; RawID definition is
48-
// an orphan {type:string}. Should be a definition the field $refs.
46+
// F2: type+model — field $refs RawID; the RawID definition is {type:string}
47+
// (the swagger:type override applied to the decl).
4948
raw := h["raw"]
50-
assert.Equal(t, []string{"string"}, []string(raw.Type))
51-
assert.Empty(t, raw.Ref.String(), "TODO F2: field should $ref RawID")
49+
assert.Equal(t, "#/definitions/RawID", raw.Ref.String())
50+
assert.Equal(t, []string{"string"}, []string(doc.Definitions["RawID"].Type))
5251

53-
// TODO F4: enum+model inlines the values on the field; the Status
54-
// definition is an orphan {type:string} with NO enum. Should be an enum
55-
// definition the field $refs.
52+
// F4: enum+model — field $refs Status; the Status definition carries the
53+
// enum values, no longer value-less.
5654
state := h["state"]
57-
assert.Equal(t, []any{"active", "closed"}, state.Enum)
58-
assert.Empty(t, state.Ref.String(), "TODO F4: field should $ref Status")
59-
assert.Empty(t, doc.Definitions["Status"].Enum, "TODO F4: definition has no enum today")
55+
assert.Equal(t, "#/definitions/Status", state.Ref.String())
56+
assert.Equal(t, []any{"active", "closed"}, doc.Definitions["Status"].Enum)
6057

61-
// F4b: BARE swagger:enum (no name) is a parse error — the enum is dropped
62-
// entirely, so Priority is a plain integer model the field $refs.
58+
// F4b (TODO Part C): bare swagger:enum (no name) still does not collect the
59+
// decl's consts — Priority is a plain integer model with no enum, and the
60+
// bare form still raises a parse error. Part C will infer the name from the
61+
// decl and collect the consts.
6362
priority := h["priority"]
6463
assert.Equal(t, "#/definitions/Priority", priority.Ref.String())
65-
assert.Empty(t, doc.Definitions["Priority"].Enum, "TODO F4: bare swagger:enum collects no values today")
64+
assert.Empty(t, doc.Definitions["Priority"].Enum, "TODO Part C: bare swagger:enum collects no values yet")
6665

6766
var bareEnumErr bool
6867
for _, d := range diags {
6968
if d.Code == grammar.CodeMissingRequiredArg {
7069
bareEnumErr = true
7170
}
7271
}
73-
assert.True(t, bareEnumErr, "bare swagger:enum currently errors (name/value-list required)")
72+
assert.True(t, bareEnumErr, "TODO Part C: bare swagger:enum still errors (name/value-list required)")
7473

7574
scantest.CompareOrDumpJSON(t, doc, "quirk_model_override_matrix.json")
7675
}

0 commit comments

Comments
 (0)
⌂ 换网址