Skip to content

Commit fb38ec4

Browse files
fredbiclaude
andcommitted
docs: doc-site coverage for DefaultAllOfForEmbeds + SkipJSONifyInterfaceMethods
Two new opt-in Options knobs landed, both shaping the "Names & $refs" surface. Document each as a test-backed how-to in the shaping-the-output/names-and-refs/ subsection, and add a row for each to the Options reference. DefaultAllOfForEmbeds — render a plain (untagged, unnamed) struct embed as an allOf composition instead of inlining its promoted properties: a $ref member when the embedded type is a model, an inline member otherwise, with the embedding struct's own fields in a sibling member. json-named embeds (#2038), swagger:allOf embeds, and interface embeds are unaffected. New how-to composing-embeds-with-allof.md (weight 35) with an off-vs-on compare; witness docs/examples/shaping/embedallof (model + non-model + pointer + json-named + tagged embeds). SkipJSONifyInterfaceMethods — emit interface-method property names verbatim (ID, CreatedAt) instead of the auto-jsonified spelling (id, createdAt). Only interface methods are affected; struct fields and swagger:name overrides are untouched. New how-to interface-method-names.md (weight 25) with an off-vs-on compare; witness docs/examples/shaping/interfacenames. Both witnesses mirror the upstream integration tests (interface-no-mangle, default-allof-embeds) and regenerate via UPDATE_GOLDEN=1. Verified: examples suite no drift, golangci-lint 0 issues, markdown lint+links clean, Hugo 77 pages 0 warn/err. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
1 parent c8fea7a commit fb38ec4

11 files changed

Lines changed: 572 additions & 0 deletions

File tree

‎docs/doc-site/maintainers/options.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,10 @@ How definitions are named and how `$ref`s render. See
5252
| Option | Type | Default | Effect |
5353
|--------|------|---------|--------|
5454
| `NameFromTags` | `[]string` | `nil` (⇒ `["json"]`) | Ordered struct-tag types a property/parameter/header name is derived from; first that supplies a name wins. Explicit empty slice ⇒ Go field name. Only the name — `json` encoding directives (`-`, `,omitempty`, `,string`) always come from `json`. See [Naming from struct tags]({{% relref "naming-from-tags" %}}). |
55+
| `SkipJSONifyInterfaceMethods` | `bool` | `false` | Emit interface-method property names verbatim (`ID`, `CreatedAt`) instead of auto-jsonifying them (`id`, `createdAt`). Only affects interface methods; struct fields and `swagger:name` overrides are unchanged. See [Interface-method property names]({{% relref "interface-method-names" %}}). |
5556
| `RefAliases` | `bool` | `false` | Render Go type aliases as a first-class `$ref` (via `swagger:model`) instead of expanding them inline. See [Alias rendering]({{% relref "alias-rendering" %}}). |
5657
| `TransparentAliases` | `bool` | `false` | Make aliases fully transparent — never creating a definition. See [Alias rendering]({{% relref "alias-rendering" %}}). |
58+
| `DefaultAllOfForEmbeds` | `bool` | `false` | Render a plain (untagged, unnamed) struct embed as an `allOf` member — a `$ref` for a model embed, an inline member otherwise — with the embedding struct's own fields in a sibling member, instead of inlining promoted properties. json-named embeds, `swagger:allOf` embeds, and interface embeds are unaffected. See [Composing embeds with allOf]({{% relref "composing-embeds-with-allof" %}}). |
5759
| `NameConcatBudget` | `float64` | `0` (⇒ `0.65`) | Readability cutoff `[0,1]` for the package-segment concatenation that deconflicts colliding definition names; lower scores are more readable. A group whose best concat scores above the budget is a candidate for the hierarchical fallback. See [Resolving `$ref` name conflicts]({{% relref "resolving-name-conflicts" %}}). |
5860
| `EmitHierarchicalNames` | `bool` | `false` | For the rare collision group whose best flat concat exceeds `NameConcatBudget`, emit nested container definitions (`#/definitions/<pkg>/<Name>`) instead of a long flat concat, with an explanatory diagnostic. The always-correct flat concat is the default. See [Resolving `$ref` name conflicts]({{% relref "resolving-name-conflicts" %}}). |
5961
| `EmitRefSiblings` | `bool` | `false` | Emit a `$ref`'d field's description and vendor extensions as direct `$ref` siblings (`{$ref, description, x-*}`) instead of an `allOf` wrap. Validations/externalDocs still force a compound. See [Descriptions beside a `$ref`]({{% relref "descriptions-beside-a-ref" %}}). |
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
title: Composing embeds with allOf
3+
weight: 35
4+
description: |
5+
Render a plain struct embed as an allOf composition — a $ref to the embedded
6+
model plus a sibling member for the embedding struct's own fields — instead of
7+
inlining the promoted properties, with DefaultAllOfForEmbeds.
8+
---
9+
10+
When a struct embeds another struct, Go *promotes* the embedded fields, and by
11+
default codescan mirrors that: the embedded type's properties are inlined flat
12+
into the embedding schema. That is faithful to the Go value, but it loses the
13+
*"this composes `Base`"* relationship — every embedding model emits its own flat
14+
copy of the embedded fields, and a client generator can't recover the shared
15+
base type.
16+
17+
`DefaultAllOfForEmbeds` changes that. With the option on, a **plain** embed (one
18+
with no explicit name and no `swagger:allOf` tag) is rendered as an `allOf`
19+
member — exactly as if it carried
20+
[`swagger:allOf`]({{% relref "/tutorials/polymorphic-models" %}}) — so the
21+
composition relationship survives in the spec. It is opt-in and defaults to off;
22+
with it off, output is byte-identical to before.
23+
24+
## What composes
25+
26+
This model embeds a `swagger:model` type (`Base`), a non-model type (`Mixin`),
27+
and adds an own field:
28+
29+
{{< code file="shaping/embedallof/embedallof.go" lang="go" region="base" >}}
30+
31+
{{< code file="shaping/embedallof/embedallof.go" lang="go" region="plain" >}}
32+
33+
Scanned with the flag off the embedded properties inline flat; on, the embed
34+
becomes an `allOf` composition:
35+
36+
{{< compare left="shaping/embedallof/testdata/plainembed_off.json" leftlabel="Default — inlined"
37+
right="shaping/embedallof/testdata/plainembed_on.json" rightlabel="DefaultAllOfForEmbeds — composed" >}}
38+
39+
Reading the composed pane, each embed takes the path its kind dictates:
40+
41+
- **A model embed becomes a `$ref` member.** `Base` is a `swagger:model`, so it
42+
has its own definition and composes as `{$ref: "#/definitions/Base"}` — no
43+
copy of `id` / `name`.
44+
- **A non-model embed becomes an inline member.** `Mixin` carries no
45+
`swagger:model`, so it has no definition to point at; its `note` property
46+
rides an inline `allOf` member instead.
47+
- **The embedding struct's own fields move to a sibling member.** `color` is no
48+
longer a top-level property — it lands in its own `allOf` arm alongside the
49+
composed embeds.
50+
51+
## What's left alone
52+
53+
The flag only changes the *untagged, unnamed* embed — every other embed shape is
54+
unaffected:
55+
56+
{{< code file="shaping/embedallof/embedallof.go" lang="go" region="edges" >}}
57+
58+
- **Pointer embeds** are peeled first, so `*Base` composes to the same
59+
`$ref` member as a value embed.
60+
- **A json-named embed is not a promotion.** Giving the embed a json tag
61+
(`Base \`json:"base"\``) makes it a single nested property named `base`, on or
62+
off — Go doesn't promote a named embed (go-swagger#2038).
63+
- **An explicit `swagger:allOf` embed already composes**, so the flag is a no-op
64+
for it; it only makes `allOf` the *default* for untagged embeds.
65+
- **Interface embeds** compose via `allOf` regardless of this flag.
66+
67+
{{% notice style="note" %}}
68+
`DefaultAllOfForEmbeds` is the global default-on switch for the same shape
69+
`swagger:allOf` produces per-embed. Reach for the annotation when only some
70+
embeds should compose; reach for the option when composition is your house style
71+
for every plain embed.
72+
{{% /notice %}}
73+
74+
## What's next
75+
76+
- [Polymorphic models]({{% relref "/tutorials/polymorphic-models" %}}) — the
77+
`swagger:allOf` annotation and discriminator hints this option generalises.
78+
- [Descriptions beside a `$ref`]({{% relref "descriptions-beside-a-ref" %}}) —
79+
how a description and validations render on an `allOf` member.
80+
- [Resolving `$ref` name conflicts]({{% relref "resolving-name-conflicts" %}}) —
81+
the definition names the composed `$ref`s point at.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
title: Interface-method property names
3+
weight: 25
4+
description: |
5+
Emit interface-method property names verbatim (ID, CreatedAt) instead of the
6+
auto-jsonified spelling (id, createdAt), with SkipJSONifyInterfaceMethods.
7+
---
8+
9+
When a model's shape is described by an **interface**, its methods have no
10+
natural JSON serialization — Go's `encoding/json` can't marshal interface
11+
methods, so there's no struct tag to read a name from. codescan invents one by
12+
running its jsonify transform on the Go method name: `ID` → `id`, `CreatedAt`
13+
→ `createdAt`. That "one size fits all" convention isn't always what you want —
14+
an interface already named for its JSON shape, or a codebase with its own
15+
canonical-name discipline, wants the Go name kept as-is.
16+
17+
`SkipJSONifyInterfaceMethods` opts out of the mangler. With it set, an
18+
interface-method property is emitted under the Go method name verbatim. It is an
19+
opt-out and defaults to off; with it off, output is unchanged.
20+
21+
## What changes
22+
23+
This model is an interface with two default-path methods and one carrying a
24+
`swagger:name` override:
25+
26+
{{< code file="shaping/interfacenames/interfacenames.go" lang="go" region="account" >}}
27+
28+
Scanned with the flag off the method names auto-jsonify; on, they ride through
29+
verbatim:
30+
31+
{{< compare left="shaping/interfacenames/testdata/account_off.json" leftlabel="Default — jsonified"
32+
right="shaping/interfacenames/testdata/account_on.json" rightlabel="SkipJSONifyInterfaceMethods — verbatim" >}}
33+
34+
Reading the two panes:
35+
36+
- **Default-path methods are jsonified.** `ID()` → `id`, `CreatedAt()` →
37+
`createdAt`; the original Go name is preserved as the `x-go-name` extension.
38+
- **With the opt-out, the Go name is the property name.** `ID` and `CreatedAt`
39+
appear verbatim — and `x-go-name` drops, since it would now just repeat the
40+
property name.
41+
- **A `swagger:name` override is verbatim either way.** `OverriddenField` is
42+
published as `explicit_name` in both panes — the override already bypasses the
43+
mangler, so the flag never touches it (and never re-mangles it to
44+
`explicitName`).
45+
46+
{{% notice style="note" %}}
47+
This flag only affects **interface methods**, which have no JSON serialization to
48+
mirror. Struct-field property names are untouched — they always reflect what
49+
`encoding/json` actually produces (see
50+
[Naming from struct tags]({{% relref "naming-from-tags" %}}) to source those from
51+
a different tag).
52+
{{% /notice %}}
53+
54+
## What's next
55+
56+
- [Naming from struct tags]({{% relref "naming-from-tags" %}}) — choose which
57+
struct tag a *field* name comes from (the struct-field analogue of this knob).
58+
- [Resolving `$ref` name conflicts]({{% relref "resolving-name-conflicts" %}}) —
59+
how the definition names themselves are kept distinct.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
// Package embedallof is the test-backed witness for the "Composing embeds with
4+
// allOf" how-to. It is scanned with DefaultAllOfForEmbeds off (an embedded
5+
// struct's properties inline into the embedding schema) and on (a plain embed
6+
// becomes an allOf member — a $ref when the embedded type is a model, an inline
7+
// member otherwise — with the embedding struct's own fields in a sibling
8+
// member). A json-named embed and an explicit swagger:allOf embed are
9+
// unaffected by the flag.
10+
package embedallof
11+
12+
// snippet:base
13+
14+
// Base is a reusable base model.
15+
//
16+
// swagger:model Base
17+
type Base struct {
18+
ID int64 `json:"id"`
19+
Name string `json:"name"`
20+
}
21+
22+
// Mixin is a non-model embedded type (no swagger:model), reachable only through
23+
// embedding. Under the flag it composes as an inline allOf member, since it has
24+
// no definition of its own to $ref.
25+
type Mixin struct {
26+
Note string `json:"note"`
27+
}
28+
29+
// endsnippet:base
30+
31+
// snippet:plain
32+
33+
// PlainEmbed embeds a model and a non-model plainly, plus an own field.
34+
//
35+
// swagger:model PlainEmbed
36+
type PlainEmbed struct {
37+
Base
38+
Mixin
39+
40+
Color string `json:"color"`
41+
}
42+
43+
// endsnippet:plain
44+
45+
// snippet:edges
46+
47+
// PointerEmbed embeds a model through a pointer; the pointer is peeled and
48+
// takes the same $ref path as a value embed.
49+
//
50+
// swagger:model PointerEmbed
51+
type PointerEmbed struct {
52+
*Base
53+
54+
Tag string `json:"tag"`
55+
}
56+
57+
// NamedEmbed embeds Base under an explicit json name, so Go does not promote
58+
// it: it stays a single nested property, identical on or off (go-swagger#2038).
59+
//
60+
// swagger:model NamedEmbed
61+
type NamedEmbed struct {
62+
Base `json:"base"`
63+
64+
Extra string `json:"extra"`
65+
}
66+
67+
// TaggedEmbed already composes Base via an explicit swagger:allOf tag, so the
68+
// flag does not change its shape.
69+
//
70+
// swagger:model TaggedEmbed
71+
type TaggedEmbed struct {
72+
// swagger:allOf
73+
Base
74+
75+
Field string `json:"field"`
76+
}
77+
78+
// endsnippet:edges
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
package embedallof
4+
5+
import (
6+
"encoding/json"
7+
"os"
8+
"path/filepath"
9+
"runtime"
10+
"testing"
11+
12+
"github.com/go-openapi/codescan"
13+
"github.com/go-openapi/spec"
14+
"github.com/go-openapi/testify/v2/assert"
15+
"github.com/go-openapi/testify/v2/require"
16+
)
17+
18+
func examplesRoot(t *testing.T) string {
19+
t.Helper()
20+
_, thisFile, _, ok := runtime.Caller(0)
21+
require.True(t, ok)
22+
return filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", ".."))
23+
}
24+
25+
// scanEmbedAllOf scans the witness tree with DefaultAllOfForEmbeds off or on.
26+
func scanEmbedAllOf(t *testing.T, on bool) *spec.Swagger {
27+
t.Helper()
28+
doc, err := codescan.Run(&codescan.Options{
29+
WorkDir: examplesRoot(t),
30+
Packages: []string{"./shaping/embedallof/..."},
31+
ScanModels: true,
32+
DefaultAllOfForEmbeds: on,
33+
})
34+
require.NoError(t, err)
35+
require.NotNil(t, doc)
36+
return doc
37+
}
38+
39+
// goldenRaw marshals an arbitrary value into testdata/<feature>.json,
40+
// honouring UPDATE_GOLDEN.
41+
//
42+
// Regenerate with: UPDATE_GOLDEN=1 go test ./...
43+
func goldenRaw(t *testing.T, feature string, v any) {
44+
t.Helper()
45+
got, err := json.MarshalIndent(v, "", " ")
46+
require.NoError(t, err)
47+
got = append(got, '\n')
48+
49+
golden := filepath.Join("testdata", feature+".json")
50+
if os.Getenv("UPDATE_GOLDEN") != "" {
51+
require.NoError(t, os.WriteFile(golden, got, 0o600))
52+
}
53+
want, err := os.ReadFile(golden)
54+
require.NoError(t, err)
55+
assert.JSONEq(t, string(want), string(got))
56+
}
57+
58+
// allOfHasRef reports whether any allOf member of sch is a $ref to ref.
59+
func allOfHasRef(sch spec.Schema, ref string) bool {
60+
for _, m := range sch.AllOf {
61+
if m.Ref.String() == ref {
62+
return true
63+
}
64+
}
65+
return false
66+
}
67+
68+
// allOfHasProp reports whether any allOf member of sch carries property name.
69+
func allOfHasProp(sch spec.Schema, name string) bool {
70+
for _, m := range sch.AllOf {
71+
if _, ok := m.Properties[name]; ok {
72+
return true
73+
}
74+
}
75+
return false
76+
}
77+
78+
// TestEmbedAllOf_Off is the control: with the flag off a plain embed inlines
79+
// the embedded type's properties (byte-identical to the historic behaviour).
80+
func TestEmbedAllOf_Off(t *testing.T) {
81+
doc := scanEmbedAllOf(t, false)
82+
pe, ok := doc.Definitions["PlainEmbed"]
83+
require.True(t, ok, "PlainEmbed definition missing")
84+
goldenRaw(t, "plainembed_off", pe)
85+
86+
// Inlined flat: every embedded + own field lands as a top-level property.
87+
assert.Empty(t, pe.AllOf, "plain embed must not compose when off")
88+
for _, p := range []string{"id", "name", "note", "color"} {
89+
_, has := pe.Properties[p]
90+
assert.True(t, has, "field %q inlined when off", p)
91+
}
92+
}
93+
94+
// TestEmbedAllOf_On exercises the feature: a plain model embed becomes an allOf
95+
// $ref member, a plain non-model embed an inline allOf member, and the embedding
96+
// struct's own fields a sibling allOf member. A json-named embed and an explicit
97+
// swagger:allOf embed are unaffected.
98+
func TestEmbedAllOf_On(t *testing.T) {
99+
doc := scanEmbedAllOf(t, true)
100+
pe, ok := doc.Definitions["PlainEmbed"]
101+
require.True(t, ok, "PlainEmbed definition missing")
102+
goldenRaw(t, "plainembed_on", pe)
103+
104+
// PlainEmbed composes; no embedded/own field is inlined at the top level.
105+
require.NotEmpty(t, pe.AllOf, "plain embed must compose into allOf when on")
106+
_, hasID := pe.Properties["id"]
107+
assert.False(t, hasID, "model embed must not inline when composing")
108+
assert.True(t, allOfHasRef(pe, "#/definitions/Base"), "model embed → $ref allOf member")
109+
assert.True(t, allOfHasProp(pe, "note"), "non-model embed → inline allOf member")
110+
assert.True(t, allOfHasProp(pe, "color"), "own field → sibling allOf member")
111+
112+
// PointerEmbed: *Base is peeled to the same $ref composition.
113+
ptr := doc.Definitions["PointerEmbed"]
114+
require.NotEmpty(t, ptr.AllOf)
115+
assert.True(t, allOfHasRef(ptr, "#/definitions/Base"), "pointer embed peels to a $ref member")
116+
assert.True(t, allOfHasProp(ptr, "tag"), "own field in sibling member")
117+
118+
// NamedEmbed: a json-named embed stays a single nested property, unaffected.
119+
named := doc.Definitions["NamedEmbed"]
120+
assert.Empty(t, named.AllOf, "a json-named embed must not compose")
121+
_, hasBase := named.Properties["base"]
122+
assert.True(t, hasBase, "named embed nests under its json name")
123+
124+
// TaggedEmbed: an explicit swagger:allOf embed is already composition.
125+
tagged := doc.Definitions["TaggedEmbed"]
126+
assert.True(t, allOfHasRef(tagged, "#/definitions/Base"), "swagger:allOf embed already composes")
127+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"type": "object",
3+
"title": "PlainEmbed embeds a model and a non-model plainly, plus an own field.",
4+
"properties": {
5+
"color": {
6+
"type": "string",
7+
"x-go-name": "Color"
8+
},
9+
"id": {
10+
"type": "integer",
11+
"format": "int64",
12+
"x-go-name": "ID"
13+
},
14+
"name": {
15+
"type": "string",
16+
"x-go-name": "Name"
17+
},
18+
"note": {
19+
"type": "string",
20+
"x-go-name": "Note"
21+
}
22+
},
23+
"x-go-package": "github.com/go-openapi/codescan/docs/examples/shaping/embedallof"
24+
}

0 commit comments

Comments
 (0)
⌂ 换网址