diff --git a/datamodel/high/node_builder.go b/datamodel/high/node_builder.go index 118048a9..49403a26 100644 --- a/datamodel/high/node_builder.go +++ b/datamodel/high/node_builder.go @@ -500,6 +500,13 @@ func (n *NodeBuilder) AddYAMLNode(parent *yaml.Node, entry *nodes.NodeEntry) *ya valueNode.Line = line } } + if b, bok := value.(*yaml.Node); bok { + if b.Kind == yaml.ScalarNode && b.Tag == "!!null" { + encodeSkip = true + valueNode = utils.CreateEmptyScalarNode() + valueNode.Line = line + } + } if !encodeSkip { var rawNode yaml.Node err := rawNode.Encode(value) diff --git a/datamodel/high/v3/document_test.go b/datamodel/high/v3/document_test.go index 27b51d72..2128b0ab 100644 --- a/datamodel/high/v3/document_test.go +++ b/datamodel/high/v3/document_test.go @@ -635,6 +635,25 @@ func TestDocument_MarshalIndention(t *testing.T) { } } +func TestDocument_Nullable_Example(t *testing.T) { + data, _ := os.ReadFile("../../../test_specs/nullable-examples.openapi.yaml") + info, _ := datamodel.ExtractSpecInfo(data) + + lowDoc, _ = lowv3.CreateDocumentFromConfig(info, datamodel.NewDocumentConfiguration()) + + highDoc := NewDocument(lowDoc) + rendered := highDoc.RenderWithIndention(2) + + if runtime.GOOS != "windows" { + assert.Equal(t, string(data), strings.TrimSpace(string(rendered))) + } + + rendered = highDoc.RenderWithIndention(4) + if runtime.GOOS != "windows" { + assert.NotEqual(t, string(data), strings.TrimSpace(string(rendered))) + } +} + func TestDocument_MarshalIndention_Error(t *testing.T) { data, _ := os.ReadFile("../../../test_specs/single-definition.yaml") info, _ := datamodel.ExtractSpecInfo(data) diff --git a/test_specs/nullable-examples.openapi.yaml b/test_specs/nullable-examples.openapi.yaml new file mode 100644 index 00000000..2df01929 --- /dev/null +++ b/test_specs/nullable-examples.openapi.yaml @@ -0,0 +1,14 @@ +openapi: 3.1.0 +components: + schemas: + Thing: + type: object + description: A nullable example. + properties: + target: + nullable: true + type: string + enum: + - staging + - production + example: \ No newline at end of file diff --git a/utils/nodes.go b/utils/nodes.go index 07a2d816..153c2bfc 100644 --- a/utils/nodes.go +++ b/utils/nodes.go @@ -67,6 +67,15 @@ func CreateIntNode(str string) *yaml.Node { return n } +func CreateEmptyScalarNode() *yaml.Node { + n := &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!null", + Value: "", + } + return n +} + func CreateFloatNode(str string) *yaml.Node { n := &yaml.Node{ Kind: yaml.ScalarNode,