Skip to content

Commit

Permalink
Fix ref unmarshal into BoolOrArrayOfString
Browse files Browse the repository at this point in the history
If a $ref has an object that declares `required` properties, helm-schema
will return the error

```
json: cannot unmarshal array into Go struct field
Schema.properties.required of type schema.BoolOrArrayOfString
```

Example:

```
{
  "bar": {
    "type": "object",
    "description": "from ref",
    "properties": {
      "baz": {
        "type": "string",
        "description": "from ref"
      }
    },
    "required": [
      "baz"
    ]
  }
}
```

Another option is setting `required` to `false`.  Both cases cause the
above error.

The fix is to implement UnmarshalJSON on BoolOrArrayOfString.
  • Loading branch information
linux2647 committed Nov 26, 2024
1 parent 1368290 commit 507df2d
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
12 changes: 12 additions & 0 deletions pkg/schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ func NewBoolOrArrayOfString(arr []string, b bool) BoolOrArrayOfString {
}
}

func (s *BoolOrArrayOfString) UnmarshalJSON(value []byte) error {
var multi []string
var single bool

if err := json.Unmarshal(value, &multi); err == nil {
s.Strings = multi
} else if err := json.Unmarshal(value, &single); err == nil {
s.Bool = single
}
return nil
}

func (s *BoolOrArrayOfString) MarshalJSON() ([]byte, error) {
if s.Strings == nil {
return json.Marshal([]string{})
Expand Down
13 changes: 13 additions & 0 deletions tests/ref_input.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,18 @@
"foo": {
"type": "string",
"description": "from ref"
},
"bar": {
"type": "object",
"description": "from different ref",
"properties": {
"baz": {
"type": "string",
"description": "from ref"
}
},
"required": [
"baz"
]
}
}
6 changes: 6 additions & 0 deletions tests/test_ref.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,9 @@
# @schema
# Not from ref
foo: bar
# @schema
# $ref: ref_input.json#/bar
# @schema
# Not from ref
bar:
baz: qux
18 changes: 17 additions & 1 deletion tests/test_ref_expected.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"bar": {
"additionalProperties": false,
"description": "from different ref",
"properties": {
"baz": {
"description": "from ref",
"required": [],
"type": "string"
}
},
"required": [
"baz"
],
"title": "bar",
"type": "object"
},
"foo": {
"default": "bar",
"description": "from ref",
Expand All @@ -18,4 +34,4 @@
},
"required": [],
"type": "object"
}
}

0 comments on commit 507df2d

Please sign in to comment.