| 69 | var yamlValidator = &validatorAdapter{validator: protovalidate.GlobalValidator} |
| 70 | |
| 71 | func FromRaw(body []byte, format RawFormat, out proto.Message, doValidate bool) error { |
| 72 | // DiscardUnknown allows contracts to include fields added in newer proto |
| 73 | // versions without breaking older CLIs that haven't been updated yet. Unlike |
| 74 | // the binary wire format, protojson/protoyaml error on unknown fields by default. |
| 75 | jsonOpts := protojson.UnmarshalOptions{DiscardUnknown: true} |
| 76 | |
| 77 | switch format { |
| 78 | case RawFormatJSON: |
| 79 | if err := jsonOpts.Unmarshal(body, out); err != nil { |
| 80 | return fmt.Errorf("error unmarshalling raw message: %w", err) |
| 81 | } |
| 82 | case RawFormatYAML: |
| 83 | // protoyaml allows validating the contract while unmarshalling |
| 84 | yamlOpts := protoyaml.UnmarshalOptions{DiscardUnknown: true} |
| 85 | if doValidate { |
| 86 | yamlOpts.Validator = yamlValidator |
| 87 | } |
| 88 | |
| 89 | if err := yamlOpts.Unmarshal(body, out); err != nil { |
| 90 | return fmt.Errorf("error unmarshalling raw message: %w", err) |
| 91 | } |
| 92 | case RawFormatCUE: |
| 93 | return errCUENotSupported |
| 94 | default: |
| 95 | return fmt.Errorf("unsupported format: %s", format) |
| 96 | } |
| 97 | |
| 98 | if doValidate { |
| 99 | if err := protovalidate.Validate(out); err != nil { |
| 100 | return fmt.Errorf("error validating raw message: %w", err) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | // IdentifyFormat does best effort to identify the format of the raw contract |
| 108 | // by going the unmarshalling path in the following order: json, yaml. |