Skip to content

Commit

Permalink
Add lower-level method SchemaToNode
Browse files Browse the repository at this point in the history
  • Loading branch information
survivorbat committed Sep 12, 2024
1 parent 6d6503f commit e36e9b9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
22 changes: 16 additions & 6 deletions scheyaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,28 @@ type config struct{}
// `description` and `examples` for documentation, `default` for default values and `properties` for listing blocks.
//
// There are currently no options available yet
func SchemaToYAML(schema []byte, _ ...Option) ([]byte, error) {
var schemaObject jsonSchema
if err := json.Unmarshal(schema, &schemaObject); err != nil {
return nil, fmt.Errorf("failed to unmarshal schema to jsonSchema object: %w", err)
func SchemaToYAML(schema []byte, opts ...Option) ([]byte, error) {
rootNode, err := SchemaToNode(schema, opts...)
if err != nil {
// Not wrapping the error because that was already done
return nil, err
}

rootNode := schemaObject.yamlExample()

result, err := yaml.Marshal(&rootNode)
if err != nil {
return nil, fmt.Errorf("failed to marshal yaml nodes: %w", err)
}

return result, nil
}

// SchemaToNode is a lower-level version of SchemaToYAML, but returns the yaml.Node instead of the
// marshalled YAML.
func SchemaToNode(schema []byte, _ ...Option) (*yaml.Node, error) {
var schemaObject jsonSchema
if err := json.Unmarshal(schema, &schemaObject); err != nil {
return nil, fmt.Errorf("failed to unmarshal schema to jsonSchema object: %w", err)
}

return schemaObject.yamlExample(), nil
}
24 changes: 24 additions & 0 deletions scheyaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)

func TestSchemaToYAML_ReturnsExpectedOutput(t *testing.T) {
Expand All @@ -28,3 +29,26 @@ func TestSchemaToYAML_ReturnsExpectedOutput(t *testing.T) {
// If the properties are as expected, test the comments
assert.Equal(t, string(expectedData), string(result))
}

func TestSchemaToNode_ReturnsExpectedOutput(t *testing.T) {
t.Parallel()
// Arrange
inputData, _ := os.ReadFile(path.Join("testdata", "test-schema.json"))

// Act
result, err := SchemaToNode(inputData)

// Assert
require.NoError(t, err)

expectedData, _ := os.ReadFile(path.Join("testdata", "test-schema-result.yaml"))

actualData, err := yaml.Marshal(result)
require.NoError(t, err)

// First test the data itself, and quit if it isn't as expected.
require.YAMLEq(t, string(expectedData), string(actualData))

// If the properties are as expected, test the comments
assert.Equal(t, string(expectedData), string(actualData))
}

0 comments on commit e36e9b9

Please sign in to comment.